Get Module File Information in Python





In Python sometimes you need to figure out where a function lives on the hard disk, or what file is calling your function. The os module provides tools for getting file and directory information and the inspect module provides the ability to inspect the stack and see what module is calling your function.

Get file information about a module

The os module in Python provides many useful ways for getting the file name of where a module lives. There are functions to get file names, directory names, and get absolute paths. Check out this example:

# Example assumes this file is named
# and lives in /home/nanodano/

import os

# Prints the full path of where the module resides

# The name of file where this print statement is written

# Get the full absolute path using os.path.abspath()
# /home/nanodano/

# Get the directory name of a file with os.path.dirname()
# Relative to current directory
# Prints an empty string if being run from current directory
# Prints .. if being called from a deeper directory

# Combine to get absolute path of the directory containing the python file
# /home/nanodano

## Other functions that might be useful
# os.path.join()  # Join directory names using system specific dir separator
# os.sep()  # Path separator character (system specific)
# os.getcwd()  # Full absolute path
# os.walk()  # Generator to walk dirs recursively
# os.listdir()  # Current dir or specific dir

Get module and file name of caller

In some cases, your function is getting called by code from other .py files. If you want to figure out where your function is being called from, you can inspect the stack. The inspect module provides a way to get this data.

import inspect

# Import this to other module and call it
def print_caller_info():
    # Get the full stack
    stack = inspect.stack()
    # Get one level up from current
    previous_stack_frame = stack[1]
    print(previous_stack_frame.filename)  # Filename where caller lives

    # Get the module object of the caller
    calling_module = inspect.getmodule(stack_frame[0])

if __name__ == '__main__':


After reading this, you should know how to get the relative and absolute filename of the current Python modules as well as modules that are calling your function.

Reference links