Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save raveensrk/95a1a2176d0d4894d7eca6ce76840e85 to your computer and use it in GitHub Desktop.
Save raveensrk/95a1a2176d0d4894d7eca6ce76840e85 to your computer and use it in GitHub Desktop.
How to find path to the module file from which a class is instantiated in system in python

In Python, you can find the path to the module file from which a class is instantiated using the inspect module. The inspect module provides functions for introspecting objects, including classes and modules. Here's an example of how you can achieve this:

import inspect
from your_module import YourClass  # Import the class you're interested in

# Get the path of the module containing the class
class_module_path = inspect.getfile(YourClass)

print("Path to the module containing the class:", class_module_path)

Replace your_module with the actual name of the module where YourClass is defined. This code will print out the path to the module file that contains the definition of the class.

Keep in mind that this approach works for modules that have a corresponding file on the filesystem. If the module is part of a package and is loaded from a directory, the path might not be as straightforward. Additionally, if the class is defined in an interactive environment like a Jupyter Notebook, the file path might not be applicable.

@raveensrk
Copy link
Author

Answer generated by chatgpt. Very useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment