Python: Calling a function from a file that has current file imported

霸气de小男生 提交于 2019-12-14 03:29:11

问题


I tried searching around but didn't seem to find an answer to my problem, so I'm sorry if I missed something and it actually has been answered before.

So basically I have main.py and another file called check.py (both in same directory)

In my main.py I have:

from check import checkfunction

I have a small function inside main.py that I MUST call inside check.py, but I can't seem to get this import working on my check.py:

from main import mainfunction

How can I get the mainfunction to work inside check.py?

Thanks!


回答1:


Several options:

  • Move the common function to a module imported by both other modules.
  • Merge both modules into one.
  • Pass the function from main to the code that needs to call it.
  • Monkey patch the function into the check module after importing it.
  • Refactor the whole thing so that you don't have circular dependencies.

If you actually explained why you have this design, someone could possibly propose a better way.




回答2:


You've got a design with a circular dependency which is usually a bad thing as your two python modules are tightly coupled.

Consider refactoring your code. But if you must stick with your design please see the following SO question for more info on how circular imports work in Python and the various gotchas to look out for.



来源:https://stackoverflow.com/questions/19332069/python-calling-a-function-from-a-file-that-has-current-file-imported

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