Home >Backend Development >Python Tutorial >How Can I Solve 'Attempted Relative Import in Non-package' Errors in Python?

How Can I Solve 'Attempted Relative Import in Non-package' Errors in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 02:21:15204browse

How Can I Solve

Relative Imports in Python: A Comprehensive Guide

The Issue: Importing Modules Across Subpackages

Imagine the following directory structure:

To import something from mod2 within the mod1 module, the following code was attempted:

However, this results in the error: "Attempted relative import in non-package."

The Solution: Declared Package

The error occurs because by running the module as __main__ by passing the mod1.py argument to the interpreter, Python treats it as a top-level module, ignoring the package information.

To resolve this issue, the __init__.py files must be properly initialized in both the sub1 and sub2 directories. This signifies that these directories are indeed packages, and we're able to import across them using relative imports.

With __init__.py files in place, the following code will successfully import mod2 within mod1:

Relative Imports and PEP 366

PEP 366 proposes a mechanism for referencing modules relative to the main module. In Python 2.6 and later versions, you can import modules relative to the main module using the following syntax:

This behavior aligns with the expected functionality for subpackage imports, ensuring a consistent and intuitive import mechanism.

The above is the detailed content of How Can I Solve 'Attempted Relative Import in Non-package' Errors in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn