Skip to content

Option to disable automatic conversion of absolute imports to relative imports in exported scripts #1537

@2catycm

Description

@2catycm

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 ImportError if not run as a module.
  • Lack of standalone execution: Users expect exported scripts to be directly runnable without requiring package context or -m flag.
  • No workaround configuration: There is currently no option (e.g., a setting in settings.ini or 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 = False

Alternatively, 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 script

With 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions