Problem Definition:
When attempting relative imports from a Python file executed as the top-level script (e.g., by typing python myfile.py), an error message is encountered: "Attempted relative import in non-package."
Understanding Module vs. Script:
The key distinction lies in how Python interprets files when loaded. When run directly as a script, a file has a name of "__main__." When imported as a module from another file, its name reflects its package structure (e.g., "package.subpackage.module").
Relative Import Restriction:
Relative imports rely on a module's full name to determine its position within the package hierarchy. If a module's name contains no package information (e.g., "__main__"), relative imports fail because the module is not considered part of a package.
Error Explanation:
When a module's full name lacks dots, indicating no package association, Python interprets it as a standalone script, and relative imports become invalid. This error occurs when:
Solutions:
Additional Notes:
The above is the detailed content of Why Do Relative Imports Fail When Running Python Scripts Directly?. For more information, please follow other related articles on the PHP Chinese website!