Recently in the development of the Smart Home Project Hestia-rpi project, due to the unreasonable hierarchy of code structure, the circular reference (import) module failed, the error is as follows:
12345678910 |
Traceback (most recent call last):
File
"./main.py"
, line 8,
in <module>
from hestiarpi.library.server
import server
File
"/home/pi/server/hestiarpi/library/server/server.py"
, line 4,
in <module>
from hestiarpi.library.brain
import handler
File
"/home/pi/server/hestiarpi/library/brain/handler.py"
, line 5,
in <module>
from hestiarpi.library.brain
import monitor
File
"/home/pi/server/hestiarpi/library/brain/monitor.py"
, line 6,
in <module>
from hestiarpi.library.server
import server
ImportError: cannot
import name server
|
Principle
There is a problem at this time, the current script Main execution, need to execute from a import, found that no A, a new A in memory, and then populate the information of a module, will go to execute a, at this time, a inside to from Main import D, So because main has been executed, directly from the memory of the map to get the main information, but at this time the main information has not been filled, because the previous is to fill before the move to a, then from the existing empty main can not get D, will error, importerror.
From: 75089682
Solution Plan A reasonable division of the project Code level
The most fundamental problem of circular reference is that the hierarchy of code is unreasonable, so the most basic and reasonable solution is to re-partition the hierarchy of code, rationalize it, and naturally evade the trouble of circular reference.
Scenario two refers only to the current package and does not refer to a specific module
If your code is this way, it works.
Before modification
123456789101112131415 |
# a.py from b Import b def a (): pass # some codes # b.py from a import a def b (): a.a () #some codes |
After modification
123456789101112131415 |
# a.py from B import b def a(): pass # some codes # b.py import A def b(): A.a.a() #some codes |
Scenario two puts a reference inside a function
If your code is this way, it works.
Before modification
123456789101112131415 |
# a.py from b Import b def a (): pass # some codes # b.py from a import a def b (): a.a () #some codes |
After modification
12345678910111213141516 |
# a.py from b import b def a (): pass # some codes # b.py def Code class= "Python Plain" >b (): from a import a a.a () #some codes |
Source: Hu Xiaoxu = a solution that fails the circular reference (import) in the Python language
View article:
- "Python" loop Import and import process
- How does the problem of looping import in Python resolve?
Recommended: Flask is a microframework for Python
A solution that fails a circular reference (import) in the Python language