Python Package Structure War: Absolute vs. Relative Imports Sparks Debate Over Runtime Speed
Local package development demands explicit boundary setting using `__init__.py` files. To streamline top-level access, the standard practice involves explicitly importing public names and listing them in `__all__`.
The community is split on import mechanics. Key architects like rtxn advocate for internal modules to use relative imports (e.g., `from .module_content import some_fn`), reserving absolute imports for the main entry point (`from lib import some_fn`). Conversely, dgdft suggests using relative imports within `__init__.py` combined with aliasing to create clean top-level namespaces. A more aggressive warning came from logging_strict: importing modules is slow, potentially introducing measurable runtime overhead, suggesting developers wait for Python 3.15's `soft import`.
The actionable consensus favors structuring directories with `__init__.py` and using relative imports internally. The major fault line remains execution timing; developers must account for immediate code execution upon import, a warning emphasized by logging_strict, over the standard mechanical fixes for imports.
Key Points
Use `__init__.py` to define package boundaries and surface public names using `__all__`.
This is the established consensus requirement for clean local package structure.
Internal dependencies should favor relative imports (`from .module import X`).
rtxn scored this highly (14), recommending it for internal module logic.
Circular dependencies risk high internal coupling.
tunetardis warned that mutual dependencies force refactoring into a shared, common module.
Import statements execute code immediately and add measurable overhead.
logging_strict strongly warned that this initialization cost must be acknowledged, pointing to SQLAlchemy as a model.
Top-level access should use relative imports within `__init__.py` combined with aliasing.
dgdft detailed this technique for surface-level package accessibility.
Source Discussions (3)
This report was synthesized from the following Lemmy discussions, ranked by community score.