Circular import dependency in Python

后端 未结 7 2141
小蘑菇
小蘑菇 2020-11-22 16:08

Let\'s say I have the following directory structure:

a\\
    __init__.py
    b\\
        __init__.py
        c\\
            __init__.py
            c_file.p         


        
7条回答
  •  Happy的楠姐
    2020-11-22 16:59

    Another solution is to use a proxy for the d_file.

    For example, let's say that you want to share the blah class with the c_file. The d_file thus contains:

    class blah:
        def __init__(self):
            print("blah")
    

    Here is what you enter in c_file.py:

    # do not import the d_file ! 
    # instead, use a place holder for the proxy of d_file
    # it will be set by a's __init__.py after imports are done
    d_file = None 
    
    def c_blah(): # a function that calls d_file's blah
        d_file.blah()
    

    And in a's init.py:

    from b.c import c_file
    from b.d import d_file
    
    class Proxy(object): # module proxy
        pass
    d_file_proxy = Proxy()
    # now you need to explicitly list the class(es) exposed by d_file
    d_file_proxy.blah = d_file.blah 
    # finally, share the proxy with c_file
    c_file.d_file = d_file_proxy
    
    # c_file is now able to call d_file.blah
    c_file.c_blah() 
    

提交回复
热议问题