Dynamic attribute introspection

Neil Hodgson nhodgson at bigpond.net.au
Tue Aug 14 06:16:50 EDT 2001


Guido van Rossum:

> With the new class system, many uses of __getattr__ can be replaced by
> descriptors for get/set attributes; see the section "Attributes
> defined by get/set methods" in the tutorial mentioned above.

   The get/set methods will provide a better solution to some but not all
uses of __getattr__. The places where __getattr__ is still best is where the
attributes are more dynamic and where there could be a cost to enumerating
the attributes.

   PEP 252 describes how a class can define its own __dict__ implementation
and that implementation could be lazy but that looks like a lot of quite
deep work. Defining __getattr__ or __setattr__ is currently simple enough
for widespread use.

> Regarding your proposed _getAttributeNames() API, how would it
> typically find the attribute names?

   In COM and XPCOM, by reading a type library or using one of the type
information APIs. With a database, by querying the database for metadata.
Often this information may be cached and so it will then be available at
lower cost. At other times, the attribute names may be truly dynamic, such
as a browser DOM which allows attributes to be added and removed from any
element in a similar manner to Python.

> > It may also prove useful to define a mechanism to provide doc
> > strings for dynamic attributes for display by development tools.
>
> The descriptor mechanism propose in PEP 252 allows for this.

   As before, implementing a new __dict__ implementation which exposes
descriptors looks like much more work than the current mechanism. There is
the possibility here to provide a generic 'dynamic object' base class to
wrap up the details so that implementing dynamic attributes remains
tractable. It would then gain some of the regularity inherent in PEP 252,
such as being able to uniformly use __dict__ to find attributes rather than
needing to add _getAttributeNames().

   Neil






More information about the Python-list mailing list