Inspect the module’s __file__ attribute (import requests; print(requests.__file__)) or call importlib.util.find_spec("module_name").origin (which resolves the file path without executing or importing the module first), wrapping the result in pathlib.Path(...).resolve() when you need an absolute, symlink-resolved path.

Basic Example

import importlib.util
from pathlib import Path
import json

# 1. Recommended (for an already-imported module): inspect `__file__`
print(json.__file__)
# Output: /usr/lib/python3.12/json/__init__.py

# Convert to a normalized Path object or find its parent directory:
json_dir = Path(json.__file__).resolve().parent
print(json_dir)
# Output: /usr/lib/python3.12/json

# 2. Recommended (WITHOUT importing/executing the module first): use importlib.util.find_spec()
spec = importlib.util.find_spec("requests")
if spec is not None and spec.origin is not None:
    print(spec.origin)
    # Output: /path/to/.venv/lib/python3.12/site-packages/requests/__init__.py

Key Details & Edge Cases

  • Packages return __init__.py; single-file modules return <name>.py (or .so / .pyd):
    • If pkg is a directory package (requests/), pkg.__file__ points to .../requests/__init__.py (use Path(pkg.__file__).parent or pkg.__path__ for the directory). If mod is a single-file module (os.py) or a compiled C extension (_sqlite3.cpython-312-x86_64-linux-gnu.so / .pyd), __file__ points directly to that file.
  • Built-in C modules compiled into the Python binary (sys, builtins, math on Windows) have NO __file__:
    • Accessing sys.__file__ raises AttributeError: module 'sys' has no attribute '__file__' (and find_spec("sys").origin returns "built-in"). Always guard with getattr(mod, "__file__", None) when inspecting arbitrary modules dynamically.
  • PEP 420 Namespace Packages (folders without __init__.py):
    • In Python 3.7+, a namespace package without __init__.py sets mod.__file__ to None (and spec.origin is None). Inspect list(mod.__path__) (or spec.submodule_search_locations) to retrieve the list of directories contributing to that namespace package.
  • importlib.util.find_spec() avoids side effects and ImportError:
    • Importing an unknown or heavyweight module just to check mod.__file__ executes its top-level code (which can open connections, load weights, or fail if optional dependencies are missing). importlib.util.find_spec("pkg.submod") searches sys.path without executing the module, returning None if not installed (note: find_spec("pkg.sub") still imports the parent package pkg to read pkg.__path__).
  • One-liner from the OS terminal (python -c):
    • Quickly verify which environment’s copy of a package is being loaded from the command line:
      python -c "import numpy; print(numpy.__file__)"
      

Comparison of Methods for Locating Imported Python Modules

Method Imports / Executes Target Module? Works on Built-in Modules (sys)? Works on Namespace Packages (No __init__.py)? Best Used When
mod.__file__ (Recommended) Yes (module is already imported) No (AttributeError) No (None — check mod.__path__) Debugging module shadowing or locating sibling assets of an already-imported module.
importlib.util.find_spec("name").origin No (for top-level modules) Returns "built-in" None (check .submodule_search_locations) Checking where a module lives (or if it is installed) without executing its import-time code.
inspect.getfile(obj) Yes (requires imported module, class, or function) No (TypeError) No (TypeError) Finding the source file where a specific function, class, or method object was defined.
python -m pip show <package> No (CLI metadata lookup) N/A Yes (shows Location: site-packages dir) Checking the installation directory of a distribution package from the terminal.