Skip to main content

How to Find the File Path of a Class in Python

Often you'll need to programmatically determine the file in which a class is defined.

This guide explores various methods for obtaining the file path of a class in Python, including techniques using inspect.getfile(), os.path.abspath(), and handling cases where you only have access to an instance of the class.

Getting the File Path with inspect.getfile()​

The inspect.getfile() method is the most direct and reliable way to get the file path of a class:

import inspect
from another import Employee # Assume Employee class is in another.py

print(inspect.getfile(Employee)) # Output (Depends on file location): /path/to/another.py
  • The inspect.getfile() returns the path to the module or source file that defined the class.

Using a Class Instance​

If you only have an instance of the class, you can access its class type and then use inspect.getfile():

import inspect
from another import Employee # Assume Employee class is in another.py

emp1 = Employee()
print(inspect.getfile(emp1.__class__)) # Output (Depends on file location): /path/to/another.py

# Alternative using type()
print(inspect.getfile(type(emp1))) # Output (Depends on file location): /path/to/another.py
  • Accessing the __class__ attribute (or using type()) provides access to the class object, which inspect.getfile() can then use to get the file path.

Getting a Relative Path​

To get a relative file path (relative to the current working directory), use os.path.relpath():

import inspect
import os
from another import Employee # Assume Employee class is in another.py


print(os.path.relpath(inspect.getfile(Employee))) # Output: another.py (if in the same directory)
  • The call to os.path.relpath() will return the location of the file, relative to where you run the python script, or a different specified directory with the start argument.

Getting the File Path with os.path.abspath()​

You can construct the absolute path manually:

import os
import sys
from another import Employee # Assume Employee class is in another.py

result = os.path.abspath(sys.modules[Employee.__module__].__file__)
print(result) # Output (Depends on file location): /path/to/another.py
  • Employee.__module__ gets the name of the module where the class is defined.
  • sys.modules[Employee.__module__] retrieves the module object.
  • __file__ is a module attribute that gives you the absolute file path, and it is then passed to os.path.abspath() to normalize the output.