-
Notifications
You must be signed in to change notification settings - Fork 513
Description
Description:
Currently, nbdev automatically converts absolute imports (e.g., import mylib.module) within the same library to relative imports (e.g., from . import module) when exporting notebooks to Python scripts. This design choice forces users to run scripts as modules (e.g., python -m mylib.module) rather than as standalone scripts (e.g., python module.py), which limits flexibility and breaks consistency between notebook execution and script execution.
Problem:
- Inconsistency: Code that runs perfectly in notebooks (using absolute imports) fails when executed directly as a script due to relative imports, causing
ImportErrorif not run as a module. - Lack of standalone execution: Users expect exported scripts to be directly runnable without requiring package context or
-mflag. - No workaround configuration: There is currently no option (e.g., a setting in
settings.inior a directive like#|script) to disable this behavior.
Proposed Solution:
Add a configuration option (e.g., in settings.ini) to preserve absolute imports during export, such as:
relative_imports = FalseAlternatively, introduce a cell-level directive (e.g., #|absolute_import) to opt out of relative import conversion for specific imports.
Why this matters:
- Maintain consistency between notebook and script execution environments.
- Enable standalone script execution without sacrificing modular development.
- Align with common Python practices where absolute imports are preferred for clarity and portability.
Example:
In a notebook:
#|export
import mylib.utils.helper # Currently becomes `from . import helper` in exported scriptWith the proposed option, it would remain as import mylib.utils.helper in the exported script.
Relevant Issue:
This issue advocates for relative imports and addresses bugs in relative import conversion. However, relative imports are not ideal for all scenarios. The core value of nbdev is that notebooks can run standalone in Jupyter/ipykernel, but exported scripts become inconsistent and rely on external module structures and PYTHONPATH configurations. This is problematic for users who need portable, self-contained scripts. Therefore, we need an option to choose between absolute and relative imports.