Relative Imports In Python
The common error, "Attempted relative import in non-package," often arises when working with relative imports in Python. This article aims to clarify the concept of relative imports and provide solutions to address this error.
Difference Between Scripts and Modules
The primary distinction lies in how Python files are loaded. A file executed directly using python myfile.py is considered a top-level script. Conversely, a file imported using an import statement within another file is a module. This distinction becomes crucial for understanding relative imports.
Importance of Naming
Upon loading, each file is assigned a name stored in the name attribute. If loaded as a script, its name is set to __main__. If imported as a module, its name reflects both the package it belongs to and the filename.
For example, in the provided directory structure:
package/ __init__.py subpackage1/ __init__.py moduleX.py moduleY.py subpackage2/ __init__.py moduleZ.py moduleA.py
Importing moduleX will assign it the name package.subpackage1.moduleX, while importing moduleA results in a name of package.moduleA. However, executing either module directly will set their name to __main__, suppressing the package information.
Relative Imports
Relative imports navigate package hierarchies using a module's name. For instance, from .. import foo indicates movement up the hierarchy. Using from .. import to ascend requires a module's name containing sufficient dots.
Non-Package Modules
However, modules with a name lacking dots are not considered part of a package. Thus, relative imports fail with the non-package error in such modules.
Solutions
To resolve the error, consider the following solutions:
The above is the detailed content of Why Do I Get 'Attempted relative import in non-package' in Python?. For more information, please follow other related articles on the PHP Chinese website!