[Python-Dev] Meta-reflections

Greg Ward gward@python.net
Mon, 18 Feb 2002 20:14:19 -0500


On 18 February 2002, Kevin Jacobs said:
> My recent post on __slots__ not being picklable (and the resounding lack of
> response to it)

Certainly caught my attention, but I had nothing to add.

>   1) Should class instances explicitly/directly know all of their attributes?

I'm not sure you're asking the right question.  If you're concerned with
introspection, shouldn't the question be: "Should arbitrary code be able
to find out the set of attributes associated with a given object?"  The
Pythonic answer is clearly yes.  And if "attribute" means "something
that follows a dot", then you can do this using dir().  Unfortunately,
the expansion of dir() to include methods means it's no longer very
useful for getting just instance attributes, whether they're in a
__dict__ or some other method.

So the obvious answer is to use vars(), which works on classic classes
and __slots__-less new-style classes.  (I think vars(x) is just a more
sociable way to spell x.__dict__.)  But it bombs on classes with
__slots__:

>>> class C(object):
...   __slots__ = ['a', 'b']
... 
>>> c = C()
>>> vars(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: vars() argument must have __dict__ attribute

Uh-oh.  This is a problem.

>   3) Should __slots__ be immutable?

Yes, definitely.  Clearly __slots__ is a property of the type (class),
not of the instance, and once the class is defined, that's it.  (Or that
should be it.)  It looks as though you can modify __slots__, but it has
no effect; that's mildly bogus.

>   4) Should __slots__ be flat?

Hmmmm... probably.  That's certainly consistent with "... once the class
is defined, that's it".

        Greg
-- 
Greg Ward - geek-at-large                               gward@python.net
http://starship.python.net/~gward/
If you and a friend are being chased by a lion, it is not necessary to
outrun the lion.  It is only necessary to outrun your friend.