Circular (or cyclic) imports in Python

前端 未结 12 2688
醉梦人生
醉梦人生 2020-11-21 05:23

What will happen if two modules import each other?

To generalize the problem, what about the cyclic imports in Python?

12条回答
  •  天命终不由人
    2020-11-21 05:39

    Ok, I think I have a pretty cool solution. Let's say you have file a and file b. You have a def or a class in file b that you want to use in module a, but you have something else, either a def, class, or variable from file a that you need in your definition or class in file b. What you can do is, at the bottom of file a, after calling the function or class in file a that is needed in file b, but before calling the function or class from file b that you need for file a, say import b Then, and here is the key part, in all of the definitions or classes in file b that need the def or class from file a (let's call it CLASS), you say from a import CLASS

    This works because you can import file b without Python executing any of the import statements in file b, and thus you elude any circular imports.

    For example:

    File a:

    class A(object):
    
         def __init__(self, name):
    
             self.name = name
    
    CLASS = A("me")
    
    import b
    
    go = B(6)
    
    go.dostuff
    

    File b:

    class B(object):
    
         def __init__(self, number):
    
             self.number = number
    
         def dostuff(self):
    
             from a import CLASS
    
             print "Hello " + CLASS.name + ", " + str(number) + " is an interesting number."
    

    Voila.

提交回复
热议问题