views:

154

answers:

1

Why would a coder stuff things into __dict__ that can't be used for attribute access? For example, in my Plone instance, dir(portal) includes index_html, but portal.index_html raises AttributeError. This is also true for the __class__ attribute of Products.ZCatalog.Catalog.mybrains. Is there a good reason why dir() can't be trusted?

Poking around the inspect module, I see they use object.__dict__['x'] instead of attribute access for this reason and because they do not want to trigger getattr magic.

+2  A: 

I don't know about Plone, so the following is general.

From the docs of dir:

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

Just guessing here, but I can think of two things that may be happening--

  • The object has a __dir__() method that returns attributes that it doesn't have

  • (less likely) The object has the attribute you're asking for (i.e. it's in obj.__dict__ or type(obj).__dict__, but overrides __getattr__ to return AttributeError

EDIT: __dir__ is only supported in Python 2.6+, however the (deprecated) special attributes __methods__ and __members__ can be used instead for earlier versions.

dF
`__dir__` is new in python 2.6, and IIRC Zope still doesn't run on anything newer than python 2.4.
Aaron Gallagher
That's true, I am using Python 2.4. Zope does not yet officially run on newer Python although it has been done experimentally.
joeforker