Import without executing module

Stephen Hansen apt.shansen at gmail.com
Tue Feb 3 23:08:34 EST 2009


On Tue, Feb 3, 2009
> So, is inserting the above if statement common practice for python
> programmers?  As a C programmer, it seems that people put a "#ifndef
> XXX...#define XXX...[all of the code]...#endif" almost as a habit.  I
> wonder if its the same thing?

That statement is very common in Python. If a module is only ever
going to be run as the main script its not needed but as you saw with
this thread, sometimes you want to import what would be main into
other places. More commonly I've found, is the use of that statement
in other modules that are never -really- meant to be main but
sometimes you want to run on their for testing or other purposes. For
me, I use it all the time in my GUI modules that are never in the
normal course of events run directly, but when developing them its
useful to quickly start up a fake app / frame and load what I'm
working on into a test display.

That said, its use is fairly unique and idiomatic just as the 'main
entry point' of a module. 75%(a number I'm pulling outta my arse!) of
its uses are things like:
    if __name__ == "__main__":
        main()

Or whatever other minimal scaffolding is required to jumpstart the
script's driver functions. Its unlikely you'll see anything like it
elsewhere -- and it serves a very different purpose from what you
describe seeing in C. There is no need to try to make sure something
is executed/compiled only once in Python like you may want to do in C.
Every module is only ever compiled once: if you import it ten times in
ten different places only the first will compile and execute the code,
the rest of the calls will return that original module again.

You're only likely to see "if" statements around definitions and
larger blocks of top-level code if someone is doing something...
complicated. Or if they're doing a big procedural script that's not
really ever meant to be re-used (especially one that grows overtime
and takes a life of its own). It happens but its really rare, from my
experience at least.

--S



More information about the Python-list mailing list