instance introspection and __slots__
Delaney, Timothy
tdelaney at avaya.com
Tue Oct 15 22:37:51 EDT 2002
> From: mertz at gnosis.cx [mailto:mertz at gnosis.cx]
>
> In my gnosis.util.introspect module which is included in
> <http://gnosis.cx/download/Gnosis_Utils-current.tar.gz>, I use the
> following implementation:
>
> class undef: pass
> def attr_dict(o, fillslots=0):
> if hasattr(o,'__dict__'):
> return o.__dict__
> elif hasattr(o,'__slots__'):
> dct = {}
> for attr in o.__slots__:
> if fillslots and not hasattr(o, attr):
> setattr(o, attr, undef())
> dct[attr] = getattr(o,attr)
> elif hasattr(o, attr):
> dct[attr] = getattr(o,attr)
> return dct
> else:
> raise TypeError, "Object has neither __dict__ nor
> __slots__"
You may want to add the case where an object has both __dict__ and
__slots__.
Using `inspect.getmembers` and `vars` can help here.
Tim Delaney
More information about the Python-list
mailing list