I am beginner. Here to learn.
A piece of code is throwing a WindowsError. I catch it and rename it to exception.
I introspect the object, through dir(exception), type(exception), print(exception.__dict__) trying to find a reference to run some documentation command on: e.g. help(areference)`.
I can't find where WindowsError was defined. I tried help(os.WindowsError) but that obviously lead to nowhere.
The ultimate intent is to locate where WindowsError comes from but for this question, as I got the answer from Google somehow, I would like to learn how to find this out through Python commands.
Specifically:
Am I introspecting wrong? Are there better ways to do that?
You probably want to give a look at the inspect module. In particular the inspect.getmodule function.
To obtain the parent classes of a class you can simply look at a class __bases__ attribute:
>>> IOError.__bases__
(<type 'exceptions.EnvironmentError'>,)
Or you can obtain the hierarchy of classes through the __mro__ attribute:
>>> IOError.__mro__
(<type 'exceptions.IOError'>, <type 'exceptions.EnvironmentError'>, <type 'exceptions.StandardError'>, <type 'exceptions.Exception'>, <type 'exceptions.BaseException'>, <type 'object'>)
The __mro__ tells you in which order python looks methods and attributes in the class hierarchy.
Note that, since python allows multiple inheritance, you cannot define the concept of "super-class". Each class can have more than one parent class, and the hierarchy can become a quite complicated graph, and trying to think of super-classes will only lead to pitfalls(e.g. calls to methods fails when the subclasses redefine the signature etc. etc.)
Question 1: Module in which a type is defined
According to my Python, it's defined in the built in module named exceptions:
>>> WindowsError
<type 'exceptions.WindowsError'>
Programmatically you can find out the module in which a type is defined by reading its __module__ attribute:
>>> WindowsError.__module__
'exceptions'
>>> sys.modules[WindowsError.__module__]
<module 'exceptions' (built-in)>
Question 2: Find the superclasses of a type
The __bases__ attribute of a type list its superclasses.
>>> WindowsError.__bases__
(<type 'exceptions.OSError'>,)
Question 3: What is the type of a given object
You didn't actually ask this question, but your comments indicate that you should have done so. To find the type of an object use the type() function.
>>> i = 666
>>> type(i)
<type 'int'>
>>> type(i).__bases__
(<type 'object'>,)
>>> type(i).__module__
'__builtin__'
So, when you catch an exception, you have an object rather than a type, that is you have an instance of the class. So to learn about the type you must first use type() to obtain the type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With