AttributeError: How to list existing attributes?

Diez B. Roggisch deets at nospam.web.de
Wed Sep 19 05:50:21 EDT 2007


Thomas Guettler wrote:

> Hi,
> 
> how can you list the attributes of an object if you catch an
> AttributeError?
> 
> I couldn't find a reference in the exception object, which
> points to the object.
> 
> I want to call dir() on the object to list the user the known
> attributes.
> 
> Is there a way to find the object by inspecting the stacktrace?

By looking at the code at the line the stacktrace lists? And at least for
me, there is a type-information as well:

Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
clWelcome to rlcompleter2 0.96
for nice experiences hit <tab> multiple times
>>> class Foo(object): pass
...
>>> f = Foo()
>>> f.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'foo'
>>>                                   

You can't possibly know which attributes the object has, though. Because it
might be an attribute dynamically added.

So the best thing is to put a print-statement before the exception-throwing
line or put a 

import pdb; pdb.set_trace()

there, and fiddle around with the object.

Diez



More information about the Python-list mailing list