When should I use a relative import in a small Python package?
Quick answer
Use a relative import when one module needs another module inside the same package and the importing module has package context. For example, from ..formatting import format_total refers from a subpackage to a module in its parent package. Use an absolute import for an application’s main entry point. If a relative import fails, check how the module was launched: running a file directly can leave it without the package context the import needs. [S1][S2]
The question, the details, the next step.
A practical checklist
Identify the importing module’s package and the target module’s location.
Use one dot for the current package and additional dots for parent-package levels. [S2]
Choose the style that makes internal dependencies clearest, and use it consistently.
Use absolute imports in the application’s main module. [S1]
Check how a module was launched when diagnosing a relative-import failure. [S2]
A few more useful answers
Does a relative import make a package more portable?
Can I use a relative import in the main script?
A module used as the application’s main module has no package context for relative imports, so use an absolute import there. [S1]
What does `from ..module import name` mean?
The two leading dots refer to parent-package levels, and module identifies a module from that level. The exact target depends on the importing module’s package. [S2]
Sources
References used for this guide.
- [S1] Python 3.13 tutorial: modules and intra-package references docs.python.org · Checked
- [S2] Python 3 import system reference: relative-import syntax and package context docs.python.org · Checked
