Home >Backend Development >Python Tutorial >How to Reliably Implement Relative Imports in Python?

How to Reliably Implement Relative Imports in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 00:16:10398browse

How to Reliably Implement Relative Imports in Python?

Implementing Relative Imports in Python

When working with a hierarchical directory structure in Python, it becomes necessary to import modules from other subdirectories. Traditional relative imports using ".." can lead to errors in certain scenarios. Particularly, when executing a module as the main module by passing it as an argument to the interpreter, relative imports fail.

According to PEP 328, relative imports rely on a module's name attribute to determine its position in the package hierarchy. However, when the name is set to '__main__', as is the case when running a module as the main module, relative imports are resolved as if the module were a top-level module, irrespective of its file system location.

To address this issue, Python 2.6 introduced the ability to reference modules relative to the main module. This is described in PEP 366. By leveraging this feature, it is possible to perform relative imports without facing the "Attempted relative import in non-package" error.

Example:

In a directory structure like:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

To import mod2 from mod1, you can use the following syntax:

from importlib.machinery import SourceFileLoader

mod2 = SourceFileLoader('mod2', 'sub2/mod2.py').load_module()

Alternatively, if you are not running the module as the main module, the usual relative import syntax will work:

from ..sub2 import mod2

The above is the detailed content of How to Reliably Implement Relative Imports 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