Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find where a Python class is defined

Tags:

python

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?

like image 939
Ivan Mushketyk Avatar asked Jul 10 '15 17:07

Ivan Mushketyk


People also ask

How to find the location of a class in Python?

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. 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:

What is a class in Python?

Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. To create a class, use the keyword class: The examples above are classes and objects in their simplest form, and are not really useful in real life applications.

How to create the object defined by a class in Python?

To create the object defined by the class, we use the constructor of the class to instantiate the object. Due to this, an object is also called an instance of a class. The constructor of a class is a special method defined using the keyword __init__(). The constructor defines the attributes of the object and initializes them as follows.

How to get the class name of a variable in Python?

Every element in a Python program is an object of a class. A number, string, list, dictionary, etc., used in a program is an object of a corresponding built-in class. You can retrieve the class name of variables or objects using the type () method, as shown below. Example: Python Built-in Classes


2 Answers

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__
like image 101
Wolph Avatar answered Sep 18 '22 21:09

Wolph


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.

like image 22
Rahul Gupta Avatar answered Sep 19 '22 21:09

Rahul Gupta