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

greg greg at cosc.canterbury.ac.nz
Mon Oct 12 04:56:37 EDT 2009


Dave Angel wrote:

> The point you should get from that link is
> 
> "Don't do circular imports.  Ever."

No, I would say the lesson to be learned from this is
"don't use the same file as both a main script and an
imported module".

I would create another file called e.g. 'main.py' that
simply contains

   import B

and use that as the main script.

Another benefit is that the compiled bytecode of B will
be saved, so it will start up faster the next time you
run it. That won't happen if you use B directly as a
main script.

(Circular imports are a different issue. There are perfectly
legitimate uses for them, and they're fine as long as you
understand the potential pitfalls and take steps to avoid
them. Although it's probably best to avoid them until you
do understand all the issues.)

-- 
Greg




More information about the Python-list mailing list