code in a module is executed twice (cyclic import problems) ?

Dave Angel davea at ieee.org
Sun Oct 11 12:46:35 CEST 2009


(please don't top-post.  Put your reply *after* the message you're quoting.)

Stef Mientki wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">thanks 
> very much Stephen,
>
> This is the first time I become aware of the difference between script 
> and module !!
> Starting with the wrong book "Learning Python" second edition, from 
> Lutz and Ascher, based on Python 2.3"
> in combination with using Python only from a high level IDE 
> (PyScripter), (never seeing the m-switch),
> I never was aware of this important difference.
> A quick Googling on "python module vs script" doesn't reveal many 
> (good) links,
> the best one I found is
>  http://effbot.org/zone/import-confusion.htm
>
> thanks again,
> Stef Mientki
> <snip>
The point you should get from that link is

"Don't do circular imports.  Ever."

It's generally worse if the circle includes the original script, treated 
as a module, but even between modules it can get you into trouble in 
many subtle ways.  Some of them cause runtime errors, so you'll "fix" 
them.  Some of them will just fail quietly, and you'll be searching for 
subtle bugs.  I don't agree with the author's "advice" that sometimes 
moving the import to the end helps.  Best advice is to break the circle, 
by "rearranging" the modules, moving commonly needed symbols into 
someplace else that both import.

It's probably safe if none of the modules in the circle has any 
top-level code that references imported symbols.  But top-level code 
includes default values for function definitions, and class initializers 
for class definitions.

Does anybody know if there's a way to activate a warning for this?

DaveA



More information about the Python-list mailing list