How to find where a Python class is defined
One way to get the location of a class is using a combination of the __module__
attribute of a class and the sys.modules
dictionary.
Example:
import sys
from stl import stl
module = sys.modules[stl.BaseStl.__module__]
print module.__file__
I should note that this doesn't always give the correct module, it just gives the module where you got it from. A more thorough (but slower) method is using the inspect
module:
from stl import stl
import inspect
print inspect.getmodule(stl.BaseStl).__file__
Let's explain by example
import numpy
print numpy.__file__
gives
/usr/lib64/python2.7/site-packages/numpy/__init__.pyc
on my machine.
If you only have a class, you can use that class with the python2-ic imp
module:
#let unknownclass be looked for
import imp
modulename = unknownclass.__module__
tup = imp.find_module(modulename)
#(None, '/usr/lib64/python2.7/site-packages/numpy', ('', '', 5))
print "path to module", modulename, ":", tup[1]
#path to module numpy : /usr/lib64/python2.7/site-packages/numpy
As you can see, the __module__
property is probably what you're looking for.
You can use the inspect
module to get the location where a module/package is defined.
inspect.getmodule(my_class)
Sample Output:
<module 'module_name' from '/path/to/my/module.py'>
As per the docs,
inspect.getmodule(object)
Try to guess which module an object was defined in.