[Tutor] Why use main() ?

Zachary Ware zachary.ware+pytut at gmail.com
Wed Jul 5 11:45:29 EDT 2017


On Wed, Jul 5, 2017 at 10:37 AM, David Rock <david.rock at gmail.com> wrote:
> This is not a question about using if __name__ == '__main__':.  I know
> what the difference is between running the script or importing it and
> using the value of __name__ to determine behavior.
>
> This is a question about the benefits of using a main() function vs not.
> ie,
>
>     if __name__ == '__main__':
>         #code goes here
>
> vs
>
>
>     def main():
>         #code goes here
>
>     if __name__ == '__main__':
>         main()
>
>
> I personally find using main() cumbersome, but many examples I come
> across use main().  Is there some fundamental benefit to using main()
> that I'm missing?

In no particular order: testing, encapsulation, and reusability.  With
a "main()" function (which, recall, can be named whatever you like; it
doesn't have to be "main") you can directly call the function in your
tests to make sure it acts the way you want.  The encapsulation of the
"main" code in a "main()" function also reduces your global state (and
makes global state a bit more difficult to use), which is usually a
good thing.  And finally, it makes it possible to use the "main()"
function in some other piece of code that imports it.

-- 
Zach


More information about the Tutor mailing list