Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Circular Import?

Reply
Thread Tools

Circular Import?

 
 
Chris S.
Guest
Posts: n/a
 
      08-28-2004
Consider the sample case:

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

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

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

## 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?
 
Reply With Quote
 
 
 
 
Benjamin Niemann
Guest
Posts: n/a
 
      08-28-2004
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)ass
>
> ## c.py
> from d import D
> class C(object)ass
>
> ## 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



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Accessing Class / Circular Reference George Durzi ASP .Net 2 06-02-2005 02:04 PM
Semi-circular definitions (plus circular references) Kiuhnm C++ 16 01-03-2005 03:49 AM
Circular References in Visual Studio =?Utf-8?B?S2VpdGggRi4=?= ASP .Net 3 08-06-2004 04:42 PM
Re: Circular References Bill Jones ASP .Net 1 04-08-2004 10:16 PM
Circular references are not supported Dan C Douglas ASP .Net 1 08-13-2003 09:21 PM



Advertisments