Import without executing module

Ray raykyoto at
Wed Feb 4 06:56:04 CET 2009

Hi Stephen,

On Feb 4, 1:08 pm, Stephen Hansen <apt.shan... at> wrote:
> 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


Oh, I see...I never thought of module testing as one possible uses of
it -- but yes, I see that now.  Makes sense to test each module
individually and (in C, at least) to write a separate main() driver in
another file each time...

> 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


Ah, ok!  I'm still trying to get use to how Python does things from
languages such as C...old habits [from other languages] are harder to
break.  :)  If the above "if" statement is fairly common, then I think
I'll start using it just to get into the habit of it.

Thank you very much for your detailed explanation!


More information about the Python-list mailing list