FEEDBACK WANTED: Type/class unification

Guido van Rossum guido at python.org
Sun Jul 29 06:01:17 EDT 2001


Paul Prescod <paulp at ActiveState.com> writes:

> I'm reading the section on the introspection API but I don't understand
> something. 
> 
> 1. If I am sitting at an interpreter prompt and I have an object how do
> I figure out the complete list of currently available attributes
> available on that object. 

Same as currently if it's a class: look in inst.__dict__ for instance
vars, then look in inst.__class__ for methods and class vars, then
recursively look through int.__class__.__bases__ for inherited methods
and class vars.  Weed out duplicates.

The new type system defines "static" and "dynamic" types.  For static
types, you don't need to search through the bases because the class
__dict__ is consolidated.  But the recursive algorithm doesn't hurt.

> 2. If I have an object that hides its attributes behind an __getattr__,
> is there any way to tweak the list returned by the API described above?
> 
> If I understand correctly, doing this is not sufficient:
> 
>  >>> T = foo.__class__
>  >>> T
>  <type 'Foo'>
>  >>> dir(T)              
> 
> I don't think that this will get base class attributes or attributes
> hidden in __getattr__. And even if it did, it would be nice to have a
> single API that combined instance attributes and class attributes
> according to the fallback rules. i.e. I'd like something as close to
> this as is realistically possible:
> 
> def attrs(x):
> 	return [y for y in all_possible_strings if hasattr(x, y)]

(Note: this may return an infinite list!)

In general, this is as impossible as it ever was -- you won't be able
to tell *for sure* whether an object has an attribute x, since
__getattr__ may be dynamic.  I added getset attributes so that for
most practical purposes you won't need to override __getattr__ so the
inspection becomes more useful.

> Take a recipe. Leave a recipe.  
> Python Cookbook!  http://www.ActiveState.com/pythoncookbook

BTW, now also linked from the python.org home page side bar.

--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-list mailing list