Python spyder debug freezes with circular importing

瘦欲@ 提交于 2019-12-25 04:22:56

问题


I have a problem with the debugger when some modules in my code call each other. Practical example:

A file dog.py contains the following code:

import cat
print("Dog")

The file cat.py is the following:

import dog
print("Cat")

When I run dog.py (or cat.py) I don't have any problem and the program runs smoothly. However, when I try to debug it, the whole spyder freezes and I have to kill the program.

Do you know how can I fix this? I would like to use this circular importing, as the modules use functions that are in the other modules.

Thank you!


回答1:


When I run dog.py (or cat.py) I don't have any problem and the program runs smoothly.

AFAICT that's mostly because a script is imported under the special name ("__main__"), while a module is imported under it's own name (here "dog" or "cat"). NB : the only difference between a script and a module is actually loaded - passed an argument to the python runtime (python dog.py) or imported from a script or any module with an import statement.

(Actually circular imports issues are a bit more complicated than what I describe above, but I'll leave this to someone more knowledgeable.)

To make a long story short: except for this particular use case (which is actually more of a side effect), Python does not support circular imports. If you have functions (classes, whatever) shared by other scripts or modules, put these functions in a different module. Or if you find out that two modules really depends on each other, you may just want to regroup them into a single module (or regroup the parts that depend on each other in a same module and everything else in one or more other modules).

Also: unless it's a trivial one-shot util or something that only depends on the stdlib, your script's content is often better reduced to a main function parsing command-line arguments / reading config files / whatever, importing the required modules and starting the effective process.



来源:https://stackoverflow.com/questions/40529469/python-spyder-debug-freezes-with-circular-importing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!