Python project import error, circular dependency

The error is as follows:

 The reason may be because of circular dependencies:

Cyclic dependency description : There are two files 1.py and 2.py under the python project. In 2.py, use from 1 import x to refer to the method x of 1.py, and at the same time want to use from 2 import in 1.py y method, here a circular dependency is generated

Solution:

In Python, mutual references between modules need to pay attention to the issue of circular dependencies. Circular dependency refers to two or more modules refer to each other's content, forming a closed loop.

In your case, 1.py references x in 2.py, and you want y in 2.py to be referenced in 1.py. If there is a circular dependency, it can cause problems with the import process.

A common way to resolve circular dependencies is to refactor the code to extract interdependent parts into a separate module, avoiding direct circular references. For example, you could create a new module, say common.py, and put the shared parts of x and y into that module. Then, 1.py and 2.py each refer to the content in common.py, not each other.

Another workaround is to use lazy imports to avoid circular dependencies. Instead of importing at the top of a module, import statements can be placed where they are needed . This can bypass import issues when circular dependencies are encountered.

In conclusion, circular dependencies are to be avoided as it leads to cluttered code structure and potential import errors. If possible, try to avoid direct circular references between modules, and consider refactoring your code or using lazy imports to resolve the issue.

おすすめ

転載: blog.csdn.net/m0_52948781/article/details/130849841