Ivan Mushketyk
Ivan Mushketyk

Reputation: 8285

How to find where a Python class is defined

Let's say I have a number in Python project and I want to find out in what package/module a particular class is defined (I know the class name). Is there an efficient way to do it?

Upvotes: 18

Views: 12943

Answers (3)

Rahul Gupta
Rahul Gupta

Reputation: 47866

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.

Upvotes: 32

Wolph
Wolph

Reputation: 80011

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__

Upvotes: 1

Marcus M&#252;ller
Marcus M&#252;ller

Reputation: 36337

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.

Upvotes: 1

Related Questions