Python notes

import_path

📘 Python Import – Relative vs Absolute

✅ Absolute Imports (e.g. from mylib.module import X)

  • Preferred for clarity and tooling support.

  • Works best for libraries intended to be installed or used across projects.

  • Compatible with IDEs, linters, static checkers.

  • Requires your project to be installed as a package, e.g. via:

    pip install -e .
  • Allows importing from outside the project, e.g.:

    from yourlib.module import something

✅ Relative Imports (e.g. from ..subpackage import helper)

  • Useful for internal module references inside a package.
  • Keeps imports local and refactor-friendly.
  • Should be avoided in scripts run directly (python module.py) — can lead to ImportError.
  • Best used when you want to decouple from the top-level package name.

❌ Problem: Relative Imports inside your library + Improper usage context

Relative imports like:

from ..subpackage import helper

are only valid when:

  • The code is run as part of a package (python -m mylib.module or via an install).
  • The importing module is not run directly, i.e., not python mylib/module1.py.

🔥 When relative imports can break things:

  1. You run a module directly (bad):

    python yourlib/module1.py  # ← ❌ relative imports like `..` will fail

    Error:

    ImportError: attempted relative import with no known parent package
  2. Another project copies or imports your file in isolation without proper package context:

    from yourlib.module1 import something  # yourlib.module1 uses relative imports internally

    If yourlib is not installed or imported as a package, the relative import may fail.

  3. Test scripts or notebooks run from a different directory without setting PYTHONPATH correctly:

    # In test/test_script.py
    from yourlib.module1 import foo  # ← works only if package is on the path

✅ Safe Approach for Public Libraries

If you're building a library that:

  • Will be installed (pip install)
  • Will be reused in other projects
  • Might be tested or executed from various contexts

Then:

Use absolute imports internally.

This avoids all the above issues because it doesn't depend on package context. Tools, IDEs, and external scripts will always know where things are coming from.


✅ Best Practices

  • Structure your project like:

    your-lib-project/
    ├── pyproject.toml (or setup.py)
    └── yourlib/
        ├── __init__.py
        ├── module1.py
        └── subpackage/
            └── helper.py
  • Install your library locally with:

    pip install -e .
  • Avoid running modules directly. Instead, use:

    python -m yourlib.module1

🧠 Rule of Thumb

Use Case Recommendation
Developing a library ✅ Prefer absolute imports
Internal refactoring ✅ Relative imports are OK
Running top-level script ✅ Absolute only
Cross-project usage ✅ Absolute only