from <module> import <resource> syntax. Using the standard import <module> syntax with dot notation will raise a SyntaxError.
Dot Notation Syntax
The dots indicate the directory level relative to the file containing the import statement:.(Single dot): The current package...(Double dot): The parent package....(Triple dot): The grandparent package.
Syntax Visualization
Consider the following package hierarchy:my_package/subpackage_a/module_x.py, relative imports are structured as follows:
Internal Mechanics
In modern Python (since PEP 451), the import system relies primarily on the module’s__spec__ attribute—specifically __spec__.parent—to resolve relative imports. Older attributes like __package__ are officially deprecated for this purpose.
When Python encounters a relative import, it calculates the target module’s absolute name by traversing up the package hierarchy. It strips levels from the current module’s package name (__spec__.parent) based on the number of leading dots, and then appends the target module name to construct the absolute import path.
- 1 dot (
.): Strips 0 levels from the parent package. - 2 dots (
..): Strips 1 level from the parent package. - 3 dots (
...): Strips 2 levels from the parent package.
Execution Constraints
Because relative imports depend on the__spec__.parent attribute to determine the package context, they cannot be used in a module that is executed directly as a top-level script.
If a file is executed directly (e.g., python module_x.py), Python treats it as the __main__ module. In this context, the module’s __spec__ attribute is None. Without a __spec__ to provide the parent package hierarchy, the import system cannot resolve the dot notation, resulting in an ImportError:
-m flag. This ensures the Python interpreter constructs the proper __spec__ before execution:
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More





