listing attributes

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Feb 14 06:03:45 EST 2006


On Mon, 13 Feb 2006 22:18:56 -0500, Peter Hansen wrote:

> Thomas Girod wrote:
>> I'm trying to get a list of attributes from a class. The dir() function
>> seems to be convenient, but unfortunately it lists to much - i don't
>> need the methods, neither the built-in variables.
>> 
>> In fact, all my variables are referencing to objects of the same type.
>> Can anyone suggest me a way to get this list of variables ?
> 
> Does the __dict__ attribute help you?  (Try viewing obj.__dict__ at the 
> interpreter prompt and see if it has what you expect. 
> obj.__dict__.keys() would be just the names of those attributes.)

>>> class Parrot(object):
...     ATTR = None
...     def method(self):
...             return None
...
>>> dir(Parrot)
['ATTR', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'method']
>>> Parrot.__dict__.keys()
['__module__', 'ATTR', 'method', '__dict__', '__weakref__', '__doc__']

So I guess the answer to that question is, while __dict__ gives less
information than dir, it still gives too much.

The thing to remember is that methods are attributes too, so it is a
little hard to expect Python to magically know which attributes you want
to see and which you don't. Although, I don't think it is too much to
expect Python to distinguish methods from non-method attributes.

However it is easy to use introspection to get what you need. 

def introspect(obj):
    attributes == dir(obj)
    # get rid of attributes that aren't the right type
    attributes = [a for a in attributes if \
    type(getattr(obj, a)) == type(obj)]
    # or filter any other way you like
    return attributes



-- 
Steven.




More information about the Python-list mailing list