Circular Import?

Discussion in 'Python' started by Chris S., Aug 28, 2004.

  1. Chris S.

    Chris S. Guest

    Consider the sample case:

    ## a.py
    import d
    import b
    b.App()

    ## b.py
    from c import C
    B = 'B'
    class App(object):pass

    ## c.py
    from d import D
    class C(object):pass

    ## d.py
    from b import B
    D = 'D'

    Executing a.py will return:
    Traceback (most recent call last):
    File "a.py", line 1, in ?
    import d
    File "d.py", line 1, in ?
    from b import B
    File "b.py", line 1, in ?
    from c import C
    File "c.py", line 1, in ?
    from d import D
    ImportError: cannot import name D

    I'm assuming this is the result of the circular imports. This isn't a
    bug, right? Is there any way around it?
    Chris S., Aug 28, 2004
    #1
    1. Advertising

  2. Chris S. wrote:

    > Consider the sample case:
    >
    > ## a.py
    > import d
    > import b
    > b.App()
    >
    > ## b.py
    > from c import C
    > B = 'B'
    > class App(object):pass
    >
    > ## c.py
    > from d import D
    > class C(object):pass
    >
    > ## d.py
    > from b import B
    > D = 'D'
    >
    > Executing a.py will return:
    > Traceback (most recent call last):
    > File "a.py", line 1, in ?
    > import d
    > File "d.py", line 1, in ?
    > from b import B
    > File "b.py", line 1, in ?
    > from c import C
    > File "c.py", line 1, in ?
    > from d import D
    > ImportError: cannot import name D
    >
    > I'm assuming this is the result of the circular imports. This isn't a
    > bug, right? Is there any way around it?

    Yep, circular imports only cause problems. Workarounds:
    - design your application not to use circular dependencies, as these are
    usually a sign for bad design
    - use late imports:

    ## foo.py
    class A:
    def a():
    import bar # instead of importing at the beginning of foo
    bar.B()

    ## bar.py
    import foo

    def B():
    pass

    class C(A):
    pass
    Benjamin Niemann, Aug 28, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kiuhnm
    Replies:
    16
    Views:
    729
    Jonathan Mcdougall
    Jan 3, 2005
  2. sw
    Replies:
    4
    Views:
    328
    Dennis Lee Bieber
    Feb 25, 2004
  3. circular import Module

    , Jun 8, 2005, in forum: Python
    Replies:
    9
    Views:
    348
    Magnus Lycka
    Jun 14, 2005
  4. Learning Python

    circular import problem

    Learning Python, Sep 9, 2005, in forum: Python
    Replies:
    1
    Views:
    418
    Terry Reedy
    Sep 9, 2005
  5. bvdp

    Circular import problem

    bvdp, Jul 13, 2007, in forum: Python
    Replies:
    10
    Views:
    442
    Alex Popescu
    Jul 15, 2007
Loading...

Share This Page