Circular imports

Edward Diener eldiener at earthlink.net
Wed May 19 19:48:17 EDT 2004


Greg Ewing wrote:
> Edward Diener wrote:
>> Can
>> anybody tell me if there are any situations where circular imports
>> cause problems and, other than a redesign to eliminate it, if there
>> are any other ways around those problems ?
>
> Circular imports can cause problems in this situation:
>
>    # module A
>    import B
>
>    def foo():
>      print "Fooey"
>
>    # module B
>    from A import foo
>
>    def blarg():
>      foo()
>
>
> If module A gets imported first, it immediately
> imports B, which tries to import foo from A before
> it's been defined.
>
> The problem can be avoided by rewriting B as follows:
>
>    # module B
>    import A
>
>    def blarg():
>      A.foo()
>
> This defers the lookup of foo in A until B.blarg
> is called, by which time A will hopefully have
> finished initialising itself.
>
> In general, if circular imports are involved, always
> use "import X" and refer to "X.n", rather than using
> "from X import n". This will avoid most circular
> import problems.

Thanks for the info. I was definitely doing some of this and causing myself
problems. Now I understand why.





More information about the Python-list mailing list