Usage of main()

Sean DiZazzo half.italian at gmail.com
Fri Sep 4 02:33:35 EDT 2009


On Sep 3, 10:55 pm, Manuel Graune <manuel.gra... at koeln.de> wrote:
> Hello everyone,
>
> the standard structure of a python-program which is taught in all of
> the books I on python I read by now is simply something like:
>
> #!/usr/bin/python
> print "Hello, world!"
> ^D
>
> While reading about structuring a larger code-base, unit-testing, etc
> I stumbled on the idiom
>
> #!/usr/bin/python
> def main():
>     print "Hello, world"
> if __name__ == "__main__":
>    main()
> ^D
>
> While experimenting with this I found that the second version in most
> cases is *a lot* faster than the simple approach. (I tried this both
> on Linux and Windows) I found this even in cases where the code con-
> sists simply of something like
>
> j=0
> for i in xrange(1000000):
>     j+=i
> print j
>
> How come the main()-idiom is not "the standard way" of writing a
> python-program (like e.g. in C)?
> And in addition: Can someone please explain why the first version
> is so much slower?
>
> Regards,
>
> Manuel
>
> --
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the worldhttp://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99

I'm trying to come up with an answer for you, but I can't...

The if __name__ == "__main__": idiom *is* the standard way to write
python programs, but it's not there to speed up programs.  It's there
so that your program can be executed differently whether it is called
as a runnable script from the command line, or if it is imported.
When you import a module, "__name__" is equal to the name of the
module, but when you execute it, it's "__name__" is "__main__"  If you
are importing a library, you generally don't want it to fire off a
bunch of processing until you call the needed functions/methods. I
also use it as a testing ground, and a sort of loose documentation for
my modules.  I put stuff in there that shows and tests a general use
of the module, but when I actually import and use it, I definitely
don't want that code to run!

What are you using to test the scripts?  I could be completely wrong,
but I find it hard to believe that the second version is much (if any)
faster than the first.  Then again, I don't know much about the
internals...

~Sean



More information about the Python-list mailing list