Home > Article > Backend Development > 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:
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:
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!