delattr()+dir() problem in 2.2b1

Tim Peters at
Sat Nov 3 07:33:56 CET 2001

[Chuck Esterbrook]
> ...
> So dir() is now returning attributes that the object doesn't really
> have, but inherits. Is that intentional?

Yes it is.  We're in the process of unifying types and classes, and one of
the most frequent complaints about the early alpha releases of 2.2 was,

>>> dir([1, 2, 3])

Note that an empty list there is entirely consistent with "classic" dir()
behavior:  the list *object* [1, 2, 3] has no attributes of its own, they're
all inherited from the list *type*.  But types and classes took entirely
different internal paths in 2.1 and before, and dir(type_instance) had
nothing in common with dir(class_instance).

Since one of the primary points of type/class unification is to whittle the
maze of artificial differences, we had to make dir() list inherited
attributes too, or break dir(type_instance) (from the POV of a 2.1 user).
Since people demonstrably bitched about the latter <wink>, we moved to the
former.  Now dir() is much more revealing:

>>> dir([1, 2, 3])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
 '__delslice__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
 '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
 '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
 '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__',
 '__setslice__', '__str__', 'append', 'count', 'extend', 'index',
 'insert', 'pop', 'remove', 'reverse', 'sort']

Unlike in 2.1, it also lists the "magic methods" list objects, umm, enjoy.

> Is there another function that I should be using to get the data
> attributes of a particular instance and no more?

for name in obj.__dict__:

should do it (and note that you can iterate over a dict's keys directly in
2.2, without *needing* to do obj.__dict__.keys() business).

More information about the Python-list mailing list