[Tutor] Why use main() ?
Danny Yoo
dyoo at hashcollision.org
Wed Jul 5 15:06:13 EDT 2017
>> 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.
I echo Zach. Python's variables are function scoped by default,
rather than block-scoped, so variables can be inadvertently introduced
that were not intended.
e.g.:
############################
>>> if __name__ == '__main__':
... x = 42
...
>>> x
42
############################
In many other languages, nesting means a new scope. In Python,
though, it doesn't, so having the main() function there allows us to
impose a scope to avoid polluting the module namespace.
More information about the Tutor
mailing list