instance introspection and __slots__
David Mertz, Ph.D.
mertz at gnosis.cx
Tue Oct 15 16:53:24 EDT 2002
"Rod Mancisidor" <mancisidor at computer.org> wrote previously:
|I used to be able to find all the direct attributes of an instance by using
|__dict__. With python 2.2 this is no longer possible since __dict__ may not
|even exist and when it does it will not include the attributes in the union
|of all the __slots__ in the MRO of the instance.
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__"
YMMV (and I might even change it later).
--
mertz@ | The specter of free information is haunting the `Net! All the
gnosis | powers of IP- and crypto-tyranny have entered into an unholy
.cx | alliance...ideas have nothing to lose but their chains. Unite
| against "intellectual property" and anti-privacy regimes!
-------------------------------------------------------------------------
More information about the Python-list
mailing list