Breaking Python Circular Imports

时间:2015-09-14 15:59:39

标签: python circular-dependency circular-reference

How to break this particular circular import. I added a trivial example added at top to highlight the issue.

module_tit.py

import tat
class Tit
    def tit(x):
        return tat.inst.tat(x)

inst = Tit()

if __name__=='__main__:
    print "tit 12 %s" % inst.tit(12)

module_tat.py

import tit
class Tat:
    def tat(x):
        if x>0:  return tit.inst.tit(x-1)
        else: return 'bottom'

inst = Tat()

if __name__=='__main__:
    print "tat 5 %s" % inst.tat(5)
  • The design of my code strongly requires that tit and tat be in their own modules.
  • It is important the either tit or tat could be the first module loaded.
  • Is this possible in python in any way???

=== original question below ===

I have a base_module with many dozens of constants etc. it is imported by many, and it imports nothing. In it I have a key class in the base module, and it depends upon a pretty printer module to do the printing of Thing:

to_str = None
class Thing_Version1(object):
    def __repr__():
        to_str(self)

In the pretty printer module I have:

def to_str(x):
    ...
import base_module
base_module.to_str = to_str  

When the pretty printer module it sets "base_module.to_str" so that everything works properly. this works 99% of the time, but in the debugger, it is not smart enough to have the pretty printer load (even though in the normal interpreter, my load process does force eventual load of pprint module. The other approach I considered was to import it dynamically:

class Thing_Version1(object):
    def __repr__():
        import pprint
        pprint.to_str(self)

But this also fails. Sometimes it cannot find the 'to_str' function in the pprint module (I assume because of circular reference)

My ultimate goal is to force loading of pprint anytime base_module loads, and allow pprint to depend on the dozens of constants in the base_module.

Is this impossible?

1 个答案:

答案 0 :(得分:1)

不幸的是我无法重现你的问题。 Python具有动态分辨率,因此循环引用很少成为问题:

fred.py

import wilma
count = 4
def main():
    wilma.pr('Hello')

wilma.py

import fred
def pr(str):
    print(str*fred.count)

Python REPL

>>> import fred
>>> fred.main()
HelloHelloHelloHello

你是否在努力避免Python中很少出现的问题? 你能提供一个遇到问题的最小例子吗?