Python exceptions: is there a way to find the exception attributes?

Pierre Rouleau pieroul at attglobal.net
Sat Nov 30 12:32:25 EST 2002


Is there a way to find out what arguments can be passed to a raised 
exception of specific class?  Python has a set of built-in exceptions 
(as described in
http://www.python.org/doc/current/lib/module-exceptions.html )

If someone needs to know what information can be passed (and retieved) 
from an IOError, one way is to go back to that document, read that 
exceptions.IOError is derived from exceptions.EnvironmentError and that 
EnvironmentError can be initiated with a 2-tuple or 3-tuple and that the 
attributes will be errno, strerror and filename.

Is there a way to find out about the existence of these attributes 
without having to read the documentation, using the dir() function or 
something else?

It would be nice to be able to do that from the interpreter.  The only 
thing i have found using dir() is shown below and it does not give me 
the attributes.

 >>> import exceptions
 >>> exceptions.IOError.__doc__
'I/O operation failed.'
 >>> dir(exceptions.IOError)
['__doc__', '__getitem__', '__init__', '__module__', '__str__']
 >>>

Of course, I could force an exception and print it like:

 >>> try:
...   f=open("/invalid/invalid.oops")
... except IOError, e:
...    print dir(e)
...
['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args', 
'errno', 'filename', 'strerror']
 >>>

Is this the only way ?




-- 
         Pierre Rouleau




More information about the Python-list mailing list