Structure your project as a package and run your entry point from the project root via python -m package.subpackage.script so you can use standard top-level imports (from shared_utils import helper) or relative parent imports (from .. import shared_utils)—and only fall back to sys.path.insert(0, str(Path(__file__).resolve().parents[1])) for standalone ad-hoc scripts that cannot be invoked as modules.
Basic Example
Assume the following directory layout:
project/
├── config.py # module in the parent directory
└── subpackage/
├── __init__.py # marks `subpackage` as a package
└── worker.py # script needing `config.py`
# Method 1 (Recommended): Package-relative or root-anchored import
# Inside project/subpackage/worker.py:
from .. import config # Relative import from parent package (requires `__init__.py` at root too)
# OR, when `project/` is the working root:
import config # Top-level import when launched via `python -m subpackage.worker`
print(config.DATABASE_URL)
# Run from the parent `project/` directory using `-m` (omit `.py` and use dots):
python -m subpackage.worker
# Method 2 (Standalone script fallback when `-m` cannot be used):
# Inside project/subpackage/worker.py:
from pathlib import Path
import sys
# Resolve parent directory reliably regardless of current working directory (cwd)
PARENT_DIR = Path(__file__).resolve().parents[1]
if str(PARENT_DIR) not in sys.path:
sys.path.insert(0, str(PARENT_DIR))
import config # Now importable even when running `python subpackage/worker.py` directly
Key Details & Edge Cases
- Why
from .. import configfails when runningpython subpackage/worker.pydirectly:- Executing a file directly by path sets
__name__ = "__main__"and__package__ = "", so Python has no parent package reference and raisesImportError: attempted relative import with no known parent package. - Relative parent imports (
from ..module import funcorfrom ...other_pkg import cls) only work when the outer parent folder also has an__init__.pyand you invoke the script viapython -m project.subpackage.workerfrom one level aboveproject/.
- Executing a file directly by path sets
- Why
Path(__file__).resolve().parents[1]beatssys.path.append(".."):- Hardcoding
sys.path.append("..")resolves".."relative to the terminal’s current working directory (os.getcwd()), not the script’s location—causingModuleNotFoundErrorwhenever the script is launched from another folder or cron job. - Using
Path(__file__).resolve().parents[1]anchors strictly to the script’s physical file path (parents[0]is the script’s own folder,parents[1]is the parent folder,parents[2]is the grandparent) and resolves symlinks safely.
- Hardcoding
- Avoid
sys.pathhacks in multi-file applications or libraries (pip install -e .):- Scattering
sys.path.insert(...)across modules causes duplicate module imports (loading the same file twice under two module names, breakingisinstance()and singletons) and confuses linters/type checkers (mypy,pyright, IDE autocomplete). - For real projects, add a minimal
pyproject.tomlin the parent root and runpip install -e .inside your virtual environment so every script, test (pytest), and subdirectory imports parent modules natively.
- Scattering
- Setting
PYTHONPATHin CI/CD or Docker without modifying code:- You can add the parent directory externally at runtime via
PYTHONPATH=. python subpackage/worker.py(Linux/macOS) or$env:PYTHONPATH="."; python subpackage/worker.py(PowerShell) without touchingsys.pathin source files.
- You can add the parent directory externally at runtime via
Comparison of Parent-Directory Import Approaches
| Approach | Syntax / Command | Requires sys.path Mutation? |
Works with pytest & IDEs? |
Best Used When |
|---|---|---|---|---|
Run as Module (python -m) |
python -m subpackage.worker + import config |
No | Yes | Structured multi-folder projects executed from the project root directory. |
Package Relative Import (..) |
from .. import config + python -m pkg.sub.worker |
No | Yes | Reusable nested packages where internal submodules reference parent package modules. |
Editable Install (pip install -e .) |
pyproject.toml + pip install -e . |
No | Yes (gold standard) | Production apps, libraries, and test suites needing clean imports everywhere. |
PYTHONPATH Environment Variable |
PYTHONPATH=/path/to/parent python sub/worker.py |
No | Partial | Docker containers, cron jobs, or CI pipelines launching scripts from arbitrary paths. |
Path(__file__).resolve().parents[1] |
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) |
Yes | Poor (breaks static analysis) | Quick one-off utility scripts inside scripts/ or notebooks/ that must run via python script.py. |
You must log in or register to comment.
