Odd behaviour of dir(object) with metaclasses.

Tim Peters tim.one at comcast.net
Wed Apr 9 17:57:09 EDT 2003


[Dirk Gerrits]
> I am a bit puzzled by the behaviour of the dir builtin.
> ...
>
> Perhaps I just don't fully understand what dir does. The first bit in
> the docs says:
>
>      Return an alphabetized list of names comprising (some of) the
>      attributes of the given object, and of attributes reachable from it:
>
> This would seem to correspond with my feeling of what its supposed to
> do, but doesn't. However, reading further, we see that the current
> behaviour is indeed as it is documented:
>
>      No argument:  the names in the current scope.
>      Module object:  the module attributes.
>      Type or class object:  its attributes, and recursively the
>          attributes of its bases.
>      Otherwise:  its attributes, its class's attributes, and recursively
>          the attributes of its class's base classes.
>
> Why is there an unnatural (IMHO) distinction between type/class objects
> and other non-module objects? I assume that a class's class is not
> considered become dir comes from the pre-metaclass era?

No, dir() was rewritten from scratch for 2.2.  The comments in the C code
say

	/* Elif some form of type or class, grab its dict and its bases.
	   We deliberately don't suck up its __class__, as methods belonging
	   to the metaclass would probably be more confusing than helpful. */

That's what Guido believed at the time, and I agreed at the time, so that's
what the code does.  Across at least seven pre-releases of 2.2, nobody
disagreed <wink>.

> Shouldn't the docs really read
> ...

No, becuase the suggested rewording doesn't describe the actual behavior --
as you noted above, the current wording does.

> ...
> I hope you'll be able to clarify these things for me a bit.

dir() was meant to be a convenience in interactive mode, and that's all.
Because of that, no two people will agree on what it "should do" in all
respects in all cases.  Changing it always makes people scream too, so I
doubt it will be changed again.  If you don't like what it does, write a dir
that does what you like -- doing so in Python is easy enough.






More information about the Python-list mailing list