How do I find the location of Python module sources?

Finding the location of Python module sources helps with debugging and understanding how modules work. Python provides several methods to locate module files depending on the module type.

Using __file__ Attribute

For pure Python modules, the __file__ attribute shows the file location ?

import os
print("Module file:", os.__file__)
print("Module location:", os.path.dirname(os.__file__))
Module file: /usr/lib/python3.8/os.py
Module location: /usr/lib/python3.8

Using inspect Module

The inspect module provides more detailed information about module sources ?

import inspect
import json

# Get source file location
print("JSON module file:", inspect.getfile(json))
print("JSON module source file:", inspect.getsourcefile(json))
JSON module file: /usr/lib/python3.8/json/__init__.py
JSON module source file: /usr/lib/python3.8/json/__init__.py

Finding Built-in Module Locations

Many built-in modules are written in C and don't have __file__ attributes. Use sys.builtin_module_names to identify them ?

import sys

# Check if a module is built-in
print("Built-in modules include:", list(sys.builtin_module_names)[:5])

# Try to get file location for built-in module
try:
    import math
    print("Math module file:", math.__file__)
except AttributeError:
    print("Math is a built-in module (no __file__ attribute)")
Built-in modules include: ['_abc', '_ast', '_codecs', '_collections', '_functools']
Math is a built-in module (no __file__ attribute)

Using sys.path to Find Module Search Paths

Check where Python searches for modules using sys.path ?

import sys

print("Python module search paths:")
for i, path in enumerate(sys.path[:3]):  # Show first 3 paths
    print(f"{i+1}. {path}")
Python module search paths:
1. 
2. /usr/lib/python38.zip
3. /usr/lib/python3.8

Comparison of Methods

Method Works For Returns
module.__file__ Pure Python modules Exact file path
inspect.getfile() Most modules File path with error handling
sys.path All modules Search directories
python -v All imports Runtime import information

Command Line Method

Run Python with the -v flag to see detailed import information including file locations. This is especially useful for built-in modules written in C.

Conclusion

Use module.__file__ for pure Python modules and inspect.getfile() for robust file location detection. For built-in C modules, check sys.builtin_module_names or use python -v to trace imports.

Updated on: 2026-03-24T17:01:12+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements