Circular (or cyclic) imports in Python

前端 未结 12 2405
醉梦人生
醉梦人生 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:45

    I got an example here that struck me!

    foo.py

    import bar
    
    class gX(object):
        g = 10
    

    bar.py

    from foo import gX
    
    o = gX()
    

    main.py

    import foo
    import bar
    
    print "all done"
    

    At the command line: $ python main.py

    Traceback (most recent call last):
      File "m.py", line 1, in 
        import foo
      File "/home/xolve/foo.py", line 1, in 
        import bar
      File "/home/xolve/bar.py", line 1, in 
        from foo import gX
    ImportError: cannot import name gX
    

提交回复
热议问题