why a main() function?
Benjamin Niemann
pink at odahoda.de
Mon Sep 18 16:10:59 EDT 2006
beliavsky at aol.com wrote:
> I think I read a suggestion somewhere to wrap the code where a Python
> script starts in a main() function, so one has
>
> def main():
> print "hi"
>
> main()
>
> instead of
>
> print "hi"
>
> What are the advantages of doing this?
Refine this to:
def main():
print "hi"
if __name__ == "__main__":
main()
The advantage of the 'if __name__ ..' statement is that you can import the
script without running the 'main' code, e.g. from your unittest module.
Wrapping the main code in a function allows you to call this function from
your unittests and test it like any other function.
Additionally I do usually add an 'argv' argument to main() which I use
instead of sys.argv, so I can easily test it with different arguments.
--
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
More information about the Python-list
mailing list