Why has 'dir()' changed in Python 2.2?

Tim Peters tim.one at home.com
Sat Feb 2 05:28:11 CET 2002


[Dr. David Mertz]
> I just noticed a change in Python 2.2... that turns out to break my
> [xml_pickle] module.  It shouldn't be hard to fix (although I *do* have
> a decision to ponder about the best fix)... but I mostly wonder what the
> thoughts behind the change were

The original intent of dir() was to list the names available from a module
object, for convenience at an interactive prompt.  As the years went on,
more gimmicks got added to it in more-or-less random fashion.

For instances of classes, the more-or-less accidental behavior that got
implemented was to list the keys of the instance's dict.

With type/class unification in 2.2, what were instances of builtin types
*became* instances of classes, and then (for example) in the early 2.2 alpha
releases you got

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

Many people complained about that.  It "was logical", since [1, 2, 3] is
indeed an instance of a class now, and doesn't have anything in its
"instance dict".  It *used* to give a listing of list methods (append, sort,
etc), because dir() dealt with instances of *types* in an entirely different
way.

With 2.2 the usefuless of that distinction vanished, and after public
discussion it was decided to make dir(instance_of_class) reveal much more
info than it used to (read the 2.2 dir.__doc__).  People who tried it in the
beta releases appeared to like it, and the complaints stopped regardless.

> (it seems like it will break a lot of code that is moderately
> introspective).

dir() is generally a poor building block for introspection, since what it
does (exactly) has always been unclear.  It's more principled in 2.2 than it
was, but since its primary *intended* use is still for convenience at an
interactive prompt, its behavior is still subject to what people claim is
convenient.  I don't know what you were using it for exactly, but chances
are good you should be looking at object.__dict__.keys() instead (which is
all dir() often did before 2.2).





More information about the Python-list mailing list