Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20949 > unrolled thread

Re: Question about circular imports

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2012-02-27 11:36 -0700
Last post2012-02-27 11:36 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Question about circular imports Ian Kelly <ian.g.kelly@gmail.com> - 2012-02-27 11:36 -0700

#20949 — Re: Question about circular imports

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-02-27 11:36 -0700
SubjectRe: Question about circular imports
Message-ID<mailman.207.1330367803.3037.python-list@python.org>
On Sun, Feb 26, 2012 at 3:42 AM, Frank Millman <frank@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web