Weird behavior on __dict__ attr

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 10 03:00:33 EST 2015


Shiyao Ma wrote:

> Hi.
> 
> My context is a little hard to reproduce.
> 
> NS3 is a network simulation tool written in C++. I am using its Python
> binding.
> 
> So the class I am dealing with is from a .so file.

So it is written in (probably) C and you don't have source code for it.

> Say, I do the following:
> 
> %
> 
> import ns.network.Node as Node
> 
> # Node is a class
> # it has a __dict__ attr
> 
> # Now I instantiate an instance of Node
> n = Node()
> 
> # I checked, there is no __dict__ on 'n'
> # but the following succeeds.
> 
> n.foobar = 3

It is hard to say exactly what is happening without source code. If Node is 
an extension class written in C, it could do almost anything. It certainly 
doesn't need to follow Python conventions for Python classes.


If this were a pure-Python class, I can think of at least three ways to get 
this behaviour:

- use __slots__ so that the class has a fixed set of members 
  with no __dict__ used or needed;

- use a custom descriptor

- use a custom metaclass that changes the behaviour of lookups;

I presume that extension classes written in C can do similar things.


> My understanding is the foobar is stored in n.__dict__, but seemingly n
> has no __dict__.
> 
> So where does the foobar go?

Here are some diagnostic tools you can use to try to determine what is going 
on:

print(vars(n))
print(dir(n))
print(n.__slots__)
o = Node.__dict__['foobar']
print(type(o), repr(o))




-- 
Steve




More information about the Python-list mailing list