Home > Backend Development > Python Tutorial > How Can I Successfully Perform Relative Imports in Python Packages?

How Can I Successfully Perform Relative Imports in Python Packages?

Patricia Arquette
Release: 2024-12-16 18:00:33
Original
779 people have browsed it

How Can I Successfully Perform Relative Imports in Python Packages?

Relative Imports in Python

In Python, importing modules from within a package can be a tricky task. Consider the following directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py
Copy after login

Suppose you're working on mod1.py and need to import something from mod2.py. You might try:

from ..sub2 import mod2
Copy after login

However, this results in an "Attempted relative import in non-package" error. The solution lies in the fact that Python interprets modules run as __main__ (e.g., python mod1.py) as top-level modules, regardless of their file system location.

To enable relative imports, the importing module must not be running as __main__. This can be accomplished by running the interpreter with a package as the main module:

python -m app.sub1.mod1
Copy after login

Alternatively, you can use the __package__ attribute to specify the parent package manually:

import sys
sys.path.insert(0, '..')
from sub2.mod2 import MyClass
Copy after login

This method manipulates the system path, but it does not require running the module as __main__.

However, for relative imports to work within subpackages, it's important to ensure that __init__.py files are present in each directory. These files act as package markers and enable the __package__ attribute to reference the containing package.

The above is the detailed content of How Can I Successfully Perform Relative Imports in Python Packages?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template