obj.__dict__ expected behavior or bug?

Raymond Hettinger vze4rx4y at verizon.net
Sun Aug 10 03:48:07 CEST 2003


"Ed Young
> Here is an example of the behavior:
> ------- code start -----------------------------------
> #!/usr/bin/python
> #bugtest - test of class attribute initiation
>
>
> class Config:
>     a = 1
>     b = 2
>     c = 3
>     d = None
>     e = None
>     h = {'d' : 22, 'e' : 33}
>
>     def __init__(self, factor):
>         for attr in self.h.keys():
>             self.__dict__[attr] = self.h[attr] * factor
>
>     def moda(self):
>         self.a *= 5
>
>
> c = Config(2)
> print c.a, c.b, c.c, c.d, c.e
> for attr in c.__dict__:
>     print 'c.%s = %s' % (attr, c.__dict__[attr])
> print
>
> c.moda()
> print c.a, c.b, c.c, c.d, c.e
> for attr in c.__dict__:
>     print 'c.%s = %s' % (attr, c.__dict__[attr])
> print
> ------- code ends -----------------------------------
> ------- output starts -------------------------------
> $ bugtest
> 1 2 3 44 66
> c.e = 66
> c.d = 44
>
> 5 2 3 44 66
> c.a = 5
> c.e = 66
> c.d = 44
> ------- output ends ---------------------------------
> What happened to c.a, c.b, and c.c when iterating thru
> c.__dict__ ?

They are up in C.__dict__



> This precludes using __dict__ as the dictionary in
> a formatted print statement.  e.g.
>
> print "c.a=%(a)s, c.b=%(b)s, c.c=%(c)s" % c.__dict__


Not really.  Use a wrapper to forward dict lookup requests
to getattr() which knows how/where to search for attributes:

class AttrDict:
    def __init__(self, obj):
        self.obj = obj
    def __getitem__(self, key):
        return getattr(self.obj, key)

print "c.a=%(a)s, c.b=%(b)s, c.c=%(c)s" % AttrDict(c)


> Is this a bug or expected behavior?

Expected.



Raymond Hettinger






More information about the Python-list mailing list