Circular import dependency in Python

后端 未结 7 2045
小蘑菇
小蘑菇 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条回答
  • 2020-11-22 17:12

    I suggest the following pattern. Using it will allow auto-completion and type hinting to work properly.

    cyclic_import_a.py

    import playground.cyclic_import_b
    
    class A(object):
        def __init__(self):
            pass
    
        def print_a(self):
            print('a')
    
    if __name__ == '__main__':
        a = A()
        a.print_a()
    
        b = playground.cyclic_import_b.B(a)
        b.print_b()
    

    cyclic_import_b.py

    import playground.cyclic_import_a
    
    class B(object):
        def __init__(self, a):
            self.a: playground.cyclic_import_a.A = a
    
        def print_b(self):
            print('b1-----------------')
            self.a.print_a()
            print('b2-----------------')
    

    You cannot import classes A & B using this syntax

    from playgroud.cyclic_import_a import A
    from playground.cyclic_import_b import B
    

    You cannot declare the type of parameter a in class B __ init __ method, but you can "cast" it this way:

    def __init__(self, a):
        self.a: playground.cyclic_import_a.A = a
    
    0 讨论(0)
提交回复
热议问题