Question about circular imports

Ian Kelly ian.g.kelly at gmail.com
Mon Feb 27 19:36:12 CET 2012


On Sun, Feb 26, 2012 at 3:42 AM, Frank Millman <frank at chagford.com> wrote:
> Hi all
>
> I seem to have a recurring battle with circular imports, and I am trying to
> nail it once and for all.
>
> Let me say at the outset that I don't think I can get rid of circular
> imports altogether. It is not uncommon for me to find that a method in
> Module A needs to access something in Module B, and a method in Module B
> needs to access something in Module A. I know that the standard advice is to
> reorganise the code to avoid this, and I try to do this where possible, but
> for now I would like to address the question of how to handle the situation
> if this is otherwise unavoidable.
>
> The problem is clearly explained in the Python Programming FAQ -
>
> "Circular imports are fine where both modules use the "import <module>" form
> of import. They fail when the 2nd module wants to grab a name out of the
> first ("from module import name") and the import is at the top level. That's
> because names in the 1st are not yet available, because the first module is
> busy importing the 2nd."
>
> [SNIP]
>
> I can think of two solutions - one is cumbersome, the other may not be good
> practice.

Solution 3: don't do the circular imports at the top level.  It's
perfectly fine to do the imports locally inside the functions that
need them, which resolves the circularity since normally the functions
won't be called until the module is fully imported.  It does add some
overhead to the functions, basically the cost of a dict lookup.

Cheers,
Ian



More information about the Python-list mailing list