Home  >  Article  >  Backend Development  >  How to Fix ModuleNotFoundError When Using Relative Imports in Python?

How to Fix ModuleNotFoundError When Using Relative Imports in Python?

DDD
DDDOriginal
2024-10-29 04:52:29768browse

 How to Fix ModuleNotFoundError When Using Relative Imports in Python?

Relative Imports in Python: Troubleshooting ModuleNotFoundError

When working with multiple Python modules, it is common to encounter the ModuleNotFoundError. This error typically occurs when attempting to import a module using a relative import path from a file that is not executed as part of a package.

To understand this error, it is important to differentiate between relative and absolute imports:

  • Absolute imports specify the full module path, regardless of the current module's location.
  • Relative imports allow importing modules relative to the current module's position within a package.

In the example provided, test.py is attempting to import config.py using a relative import path (import config). However, when test.py is not run as part of a package (such as when executed directly as a script), main will be the current module, which is not contained within a package.

Therefore, a relative import cannot be used from the main module. Instead, you should utilize absolute imports (from . import config). However, using absolute imports without adding the containing folder (ryan) to sys.path will result in a ModuleNotFoundError.

To resolve this issue, you must either:

  • Modify your directory structure and execute the script from within the package directory, ensuring that sys.path includes the package path.
  • Utilize a package-aware import method, such as inserting __init__.py files into the subdirectories that define packages.

Once these steps are in place, both absolute and relative imports should function as expected.

The above is the detailed content of How to Fix ModuleNotFoundError When Using 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