Python Relative Import From Sibling Directory

7 min read

Relative imports in Python allow developers to reference modules based on their position within a package hierarchy rather than relying on absolute paths from the project root. This mechanism becomes essential when structuring applications into logical sub-packages, particularly when a module needs to access functionality located in a sibling directory—a folder sitting at the same level in the directory tree. Mastering this syntax prevents the dreaded ImportError and ModuleNotFoundError exceptions that plague developers transitioning from simple scripts to complex package architectures And it works..

Understanding the Package Hierarchy

Before diving into syntax, it is critical to visualize the file structure. Python treats directories containing an __init__.On top of that, py file (implicit in Python 3. 3+ via namespace packages, but explicit is still best practice) as packages.

my_project/
├── main.py
└── package/
    ├── __init__.py
    ├── subpackage_a/
    │   ├── __init__.py
    │   └── module_a.py
    └── subpackage_b/
        ├── __init__.py
        └── module_b.py

In this scenario, subpackage_a and subpackage_b are siblings. So they share the same parent: package. In practice, if module_a. And py needs to import a class or function from module_b. py, it cannot use a standard import like import module_b because Python looks for module_b inside subpackage_a or the sys.path root, not sideways Less friction, more output..

The Dot Notation Syntax

Python uses leading dots (.) in from statements to denote relative positioning.

  • One dot (.): Represents the current package (directory).
  • Two dots (..): Represents the parent package (one level up).
  • Three dots (...): Represents the grandparent package (two levels up), and so on.

To import from a sibling directory, you must first deal with up to the parent package, then down into the target sibling.

The Standard Pattern: from .. import sibling_module

Inside module_a.py (located in subpackage_a), the correct syntax to access module_b.py (located in subpackage_b) is:

# Inside package/subpackage_a/module_a.py
from ..subpackage_b import module_b

# Or importing a specific object
from ..subpackage_b.module_b import specific_function, SpecificClass

Breakdown of ..subpackage_b:

  1. .. moves the context up from subpackage_a to package.
  2. subpackage_b moves the context down into the sibling directory.
  3. module_b targets the specific file.

Practical Implementation Example

Let’s flesh out the example with actual code to demonstrate the flow.

File: package/subpackage_b/module_b.py

# package/subpackage_b/module_b.py
def greet_from_b(name: str) -> str:
    return f"Hello {name}, this is Module B speaking!"

class DataProcessor:
    def process(self, data: list) -> list:
        return [item.upper() for item in data]

File: package/subpackage_a/module_a.py

# package/subpackage_a/module_a.py
# Relative import from sibling directory (subpackage_b)
from ..subpackage_b.module_b import greet_from_b, DataProcessor

def run_a():
    print("Module A is running...")
    
    # Using imported function
    message = greet_from_b("Developer")
    print(message)
    
    # Using imported class
    processor = DataProcessor()
    raw_data = ["apple", "banana", "cherry"]
    processed = processor.process(raw_data)
    print(f"Processed data: {processed}")

if __name__ == "__main__":
    run_a()

File: main.py (Entry Point)

# main.py
from package.subpackage_a.module_a import run_a

if __name__ == "__main__":
    run_a()

Running python main.py from the my_project root directory executes successfully because the interpreter resolves the relative path based on the package structure anchored at package.

The Critical Constraint: Execution Context

This is the most common stumbling block. Relative imports only work when the module is executed as part of a package.

If you figure out into package/subpackage_a/ and run python module_a.py directly, Python treats module_a.py as a top-level script (the __main__ module). It strips away the package context. This means the `..

ImportError: attempted relative import with no known parent package

Solutions for Direct Execution

If you must run a module directly while preserving relative imports, you have two solid options:

1. The -m Switch (Recommended)

Execute the module from the project root using the -m flag. This tells Python to run the module as part of the package hierarchy Small thing, real impact..

# Run from 'my_project/' root directory
python -m package.subpackage_a.module_a

This preserves the package structure, allowing .. to resolve correctly to package Not complicated — just consistent..

2. Adjusting sys.path (Legacy/Scripting Approach)

If you cannot use the -m switch (e.g., specific IDE configurations or legacy entry points), you can manually inject the project root into sys.path at runtime. This converts relative imports into absolute imports effectively.

# Inside module_a.py (Top of file)
import sys
from pathlib import Path

# Add project root (my_project) to sys.path
# __file__ -> .../my_project/package/subpackage_a/module_a.py
# parents[2] -> .../my_project/
project_root = Path(__file__).resolve().parents[2]
if str(project_root) not in sys.path:
    sys.path.insert(0, str(project_root))

# Now you CAN use absolute imports from root
from package.subpackage_b.module_b import greet_from_b

Note: While functional, modifying sys.path is generally discouraged in modern packaging standards because it can lead to namespace collisions and makes the code less portable.

Absolute Imports vs. Relative Imports

PEP 8 — the Style Guide for Python Code — explicitly recommends absolute imports for most scenarios because they are more readable and explicit That's the part that actually makes a difference..

Absolute Import Equivalent (in module_a.py):

from package.subpackage_b.module_b import greet_from_b

When to Use Which?

Scenario Recommendation
Large, deep package structures Relative imports (`from .. And
Flat structures / Top-level modules Absolute imports (from package. So ) reduce verbosity and make refactoring (moving subpackages) easier. So `) are clearer. Also, module import ... sibling import ...Consider this:
Explicit sibling access Relative imports (`from .. On the flip side, import ...
Avoiding ambiguity Absolute imports prevent confusion if a standard library module shares a name with a local package. `) clearly signal "I am reaching sideways," which aids readability for maintainers.

A common hybrid strategy: **Use absolute imports for external dependencies and top-level internal packages; use relative imports for tight coupling within a sub-package cluster (e.Day to day, g. , siblings) And it works..

Handling Namespace Packages (Missing __init__.py)

Since Python 3.3 (PEP 420), directories without __init__.py are treated as namespace packages. That said, while this allows splitting a single package across multiple directories (e. That said, g. , vendor distributions), it complicates relative imports But it adds up..

Relative imports require a regular package (with __init__.py) as an anchor.

If package/ lacks __init__.py, subpackage_a and `sub

Handling Namespace Packages (Missing __init__.py)

Since Python 3.This lets a single project’s components live in separate trees without forcing every directory to contain the special file. pyare recognized as **namespace packages**. Here's the thing — 3 (PEP 420), directories that lack aninit. That said, it creates a problem for relative imports, which rely on a clear, hierarchical structure anchored by a regular package Not complicated — just consistent..

**

If package/ lacks __init__.So py, subpackage_a and subpackage_b become part of a namespace package, allowing them to be imported as a cohesive unit without triggering the relative import machinery. Still, this creates a subtle but important constraint: relative imports (using dots) will fail because the interpreter cannot determine a reliable anchor for the current package. As a result, you must always use absolute imports to reference modules within the same tree. Even though namespace packages are supported by default in Python 3.3+, they are not a silver bullet—they merely shift the problem from import resolution to structural organization.

Practical Guidelines for Namespace Packages

When working with namespace packages, treat them as independent logical modules. In practice, pyfile can still be omitted, but you should confirm that the parent package itself contains aninit. If you need to expose public APIs from the namespace, consider defining __all__ in the top-level __init__.py to maintain a proper hierarchy. Now, the __init__. py to control what gets imported when someone runs from package import *.

A common pattern for maintaining compatibility across different Python versions is to include a minimal __init__.py that simply re-exports the public symbols from submodules, effectively bridging the gap between namespace and regular package semantics:

# package/__init__.py
from .subpackage_a import greet_from_a
from .subpackage_b import greet_from_b

This approach makes the namespace package feel like a conventional package to end‑users, while still allowing you to keep the internal layout flexible and modular.

Summary

To keep it short, absolute imports are the preferred default for clarity, maintainability, and portability. They are especially valuable in large codebases where deep hierarchies can quickly become confusing. Relative imports should be reserved for tight coupling within a sub‑package cluster, where they provide explicit signaling about direction (up, down, or across siblings). When dealing with namespace packages, remember that absolute imports remain the only safe path for intra‑tree references, and that the absence of __init__.py does not grant you freedom from the need for absolute paths—it merely relaxes the requirement for explicit package anchoring.

By adhering to these conventions, you reduce the likelihood of subtle bugs such as accidental name collisions, import loops, and fragile paths that break when the project structure is refactored. The guidelines outlined above will help you write code that is both reliable and easy to understand, aligning with the spirit of PEP 8 and modern Python packaging best practices.

Just Added

Just Went Up

Explore a Little Wider

Others Found Helpful

Thank you for reading about Python Relative Import From Sibling Directory. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home