[Python-Dev] Meta-reflections (original) (raw)

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 "", 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.