Monday, December 6, 2010

get full inherited __dict__

Edit: whoops, don't do this: use inspect.getmembers()

>>> def get_full_dict(obj):
...    return dict(sum([cls.__dict__.items() for cls in obj.__class__.__mro__ if cls.__name__ != "object"], obj.__dict__.items()))
...
>>> class A(object):
...    testA = "A"
...    testB = "A"
...    testb = "A"
...
>>> class B(A):
...    testB = "B"
...    testb = "B"
...
>>> b = B()
>>> b.testb = "b"
>>> get_full_dict(b)
{'__module__': '__main__', 'testA': 'A', 'testb': 'b', 'testB': 'B', '__dict__': <attribute '__dict__' of 'A' objects>,  __weakref__': <attribute '__weakref__'of 'A' objects>, '__doc__': None}

Returns the full dictionary of things that will be searched through by default by getattr(obj), other than a few special case variables like __doc__ and __class__.  Stops short of "object"  for clarity of sample output.  This could easily be removed if desired.

Note the reversed order of a,b in the argument list and body of the lambda expression.  This is critical in order that the subclass attributes (which will be contained in a) override the superclass attributes (which will be contained in b).

1 comment:

  1. Thanks for sharing an information to us. If someone want to know about Ethical Hacking. I think this is the right place for you!ceh Training

    ReplyDelete