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

Hendrik van Rooyen hendrik at
Sun Oct 11 08:54:54 CEST 2009

On Sunday, 11 October 2009 02:24:34 Stephen Hansen wrote:

> It's really better all around for "modules" to be considered like
> libraries, that live over There, and aren't normally executed. Then you
> have scripts over Here which may just be tiny and import a module and call
> that module's "main" method. Okay, I'm not arguing you should never execute
> a module, sometimes its useful and needful-- especially for testing or more
> complex project organization. But in general... this is just gonna cause no
> end of suffering if you don't at least try to maintain the "script" vs
> "module" mental separation. Modules are the principle focus of code-reuse
> and where most things happen, scripts are what kickstart and get things
> going and drive things. IMHO.
> If not that, then at least make sure that nothing is ever /executed/ at the
> top-level of your files automatically; when imported call 'module.meth()'
> to initialize and/or get My_List or whatever, and when executed use the
> __name__ == "__main__" block to do whatever you want to do when the file is
> started as a main script.
> Otherwise, things'll get weird.
> ... gah snip huge write-up I threw in about how we organize our code around
> the office. Not important! Your use-case is probably different enough that
> you'd surely organize differently. But still, I really recommend treating
> "modules" like static repositories of code that "scripts" call into /
> invoke / execute. Even if sometimes you execute the modules directly (and
> thus use a main() function to run in whatever default way you choose).

I have been using the __name__== "main" part of what you call modules to do 
the test code for the module.  So if you execute it at the top level, it does 
its testing, and if you import it, it is like a library.   This works for me, 
but it is probably not of general use - the stuff we do tends to be smallish 
and long running.

- Hendrik

More information about the Python-list mailing list