Use a direct module import (from helper import MyClass) for a file in the same directory or a dotted package path (from utils.helper import MyClass) for a subdirectory—and when importing from within a package module, use relative dot imports (from .helper import MyClass or from .utils.helper import MyClass) while executing your entry point from the project root via python -m package.main.
Basic Example
Assume the following directory layout:
project/
├── main.py
├── models.py # defines `class User`
└── services/
├── __init__.py # marks `services` as a regular package (recommended)
└── auth.py # defines `class AuthService`
# Inside project/main.py:
# 1. Import a class from another file in the SAME directory
from models import User
# 2. Import a class from a file inside a SUBDIRECTORY
from services.auth import AuthService
user = User("Alice")
auth = AuthService()
# Inside project/services/auth.py (importing from sibling or parent inside a package):
# 3. Relative import from the same package directory (requires running via `python -m`)
from .tokens import TokenGenerator
# 4. Relative import from the parent package directory
from ..models import User
Key Details & Edge Cases
- Why
python services/auth.pyfails withImportError: attempted relative import with no known parent package:- Running a file directly (
python services/auth.py) sets its__name__to"__main__"and strips its parent package context (__package__ == ""), causing any relative import (from .tokens import ...orfrom ..models import ...) to crash. - Always run modules inside packages from the root directory using
python -m services.authso Python resolves the package hierarchy properly.
- Running a file directly (
- Keep
__init__.pyin subdirectories (Regular Packages vs. PEP 420 Namespace Packages):- Although Python 3.3+ allows importing from a folder without
__init__.pyas an implicit namespace package, adding an empty__init__.pyfile makes it an explicit regular package—preventing subtle path collisions with installed third-party packages of the same name and ensuring test runners likepytestdiscover the package reliably.
- Although Python 3.3+ allows importing from a folder without
- Avoid filename shadowing with standard library or third-party modules:
- Naming a local file
email.py,json.py,random.py, orpandas.pyin the same directory causesfrom email import ...(and internal standard library imports) to load your local file instead of Python’s built-in module, resulting in confusingAttributeErrororImportErrorcrashes.
- Naming a local file
- Re-exporting classes cleanly at the package level (
services/__init__.py):- You can expose
from .auth import AuthServiceinsideservices/__init__.pyso callers can writefrom services import AuthServiceinstead of the deeperfrom services.auth import AuthService.
- You can expose
- Importing dynamically from an arbitrary folder outside
sys.path:- Avoid mutating
sys.path.append(...)in production code. Instead, structure your project with apyproject.tomland install it in editable mode (pip install -e .) inside your virtual environment so every folder and test suite imports packages consistently.
- Avoid mutating
Comparison of Local & Subdirectory Import Patterns
| Location of Target File | Caller Context | Recommended Syntax | How to Run Entry Point | Best Used When |
|---|---|---|---|---|
Same directory (models.py) |
Top-level script (main.py) |
from models import User |
python main.py |
Importing from a sibling module in a flat script directory. |
Subdirectory (services/auth.py) |
Top-level script (main.py) |
from services.auth import AuthService |
python main.py |
Importing from a nested package folder from the project root. |
Same package (services/tokens.py) |
Module inside services/ |
from .tokens import TokenGenerator |
python -m services.auth |
Internal imports between sibling modules inside a reusable package. |
Parent package (models.py) |
Module inside project/services/ |
from ..models import User |
python -m project.services.auth |
Accessing shared models/utilities one level up inside a multi-level package. |
Re-exported in __init__.py |
Any external caller | from services import AuthService |
python main.py |
Providing a clean public API facade for a subpackage. |
You must log in or register to comment.
