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