How do you import a Python class from the same directory or a subdirectory? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you import a Python class from the same directory or a subdirectory?

message-square
0

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.py fails with ImportError: 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 ... or from ..models import ...) to crash.
    • Always run modules inside packages from the root directory using python -m services.auth so Python resolves the package hierarchy properly.
  • Keep __init__.py in subdirectories (Regular Packages vs. PEP 420 Namespace Packages):
    • Although Python 3.3+ allows importing from a folder without __init__.py as an implicit namespace package, adding an empty __init__.py file makes it an explicit regular package—preventing subtle path collisions with installed third-party packages of the same name and ensuring test runners like pytest discover the package reliably.
  • Avoid filename shadowing with standard library or third-party modules:
    • Naming a local file email.py, json.py, random.py, or pandas.py in the same directory causes from email import ... (and internal standard library imports) to load your local file instead of Python’s built-in module, resulting in confusing AttributeError or ImportError crashes.
  • Re-exporting classes cleanly at the package level (services/__init__.py):
    • You can expose from .auth import AuthService inside services/__init__.py so callers can write from services import AuthService instead of the deeper from services.auth import AuthService.
  • Importing dynamically from an arbitrary folder outside sys.path:
    • Avoid mutating sys.path.append(...) in production code. Instead, structure your project with a pyproject.toml and install it in editable mode (pip install -e .) inside your virtual environment so every folder and test suite imports packages consistently.

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.