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
pkgis a directory package (requests/),pkg.__file__points to.../requests/__init__.py(usePath(pkg.__file__).parentorpkg.__path__for the directory). Ifmodis 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.
- If
- Built-in C modules compiled into the Python binary (
sys,builtins,mathon Windows) have NO__file__:- Accessing
sys.__file__raisesAttributeError: module 'sys' has no attribute '__file__'(andfind_spec("sys").originreturns"built-in"). Always guard withgetattr(mod, "__file__", None)when inspecting arbitrary modules dynamically.
- Accessing
- PEP 420 Namespace Packages (folders without
__init__.py):- In Python 3.7+, a namespace package without
__init__.pysetsmod.__file__toNone(andspec.originisNone). Inspectlist(mod.__path__)(orspec.submodule_search_locations) to retrieve the list of directories contributing to that namespace package.
- In Python 3.7+, a namespace package without
importlib.util.find_spec()avoids side effects andImportError:- 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")searchessys.pathwithout executing the module, returningNoneif not installed (note:find_spec("pkg.sub")still imports the parent packagepkgto readpkg.__path__).
- Importing an unknown or heavyweight module just to check
- 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__)"
- Quickly verify which environment’s copy of a package is being loaded from the command line:
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. |
You must log in or register to comment.