Python2.2 doesn't give members of a list

Tim Peters tim.one at home.com
Wed Aug 8 23:41:08 EDT 2001


[Joonas Paalasmaa]
> Why doesn't python22a1 give members of a list with dir(list).
> See snippet below.
>
>
> C:\>python22
> Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> dir([])
> []
> >>>
> C:\>python20
> Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> dir([])
> ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
>  'reverse', 'sort']

It's a peculiar side-effect of finally making sense <wink>.  Here from 2.1:

>>> class C:
...     def __init__(self, a):
...         self.a = a
...     def printa(self):
...         print self.a
...
>>> x = C(42)
>>> dir(x)  # no 'printa'!
['a']
>>>

That is, it's always been the case that dir(class_instance) didn't display
the methods of the class of which class_instance was an instance.  But
objects of builtin types were not instances of classes, so dir() did
something entirely different for them.  This is one consequence of the
infamous "type/class split":  objects of builtin types and objects of
user-defined classes act differently in subtle ways.  2.2 aims to repair
that.

In 2.2, the builtin types *are* classes, so in a funny sense dir() now acts
more like it always did than it ever did before <wink>.  Here from 2.2:

>>> dir([])
[]
>>> dir(type([]))
['__add__', '__class__', '__contains__', '__delitem__', '__eq__',
 '__ge__', '__getattr__', '__getitem__', '__getslice__', '__gt__',
 '__iadd__', '__imul__', '__init__', '__le__', '__len__', '__lt__',
 '__mul__', '__ne__', '__new__', '__repr__', '__rmul__', '__setitem__',
 '__setslice__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
 'remove', 'reverse', 'sort']
>>>

[] is now an instance of the list class, and has no interesting attributes
of its own.  So dir([]) has nothing to say.  But []'s *class* (type([]),
which is list) has many interesting attributes, and indeed dir(type([])) is
much more accurate about what they really are than was the special-case hack
used for dir([]) in 2.1 and earlier.

The new scheme is better because more consistent and predictable, but the
change in dir(builtin_object) is starting to look like it *may* be a bad
incompatibility with 2.1.  Much as I hate doing it, for this reason I'm
going to look into hacking inconsistent surprises back into dir().

although-nothing-can-make-everyone-happy-ly y'rs  - tim





More information about the Python-list mailing list