Just a quick question about main()

Thomas Jollans tjol at tjol.eu
Fri Oct 27 14:30:31 EDT 2017


On 27/10/17 20:05, ROGER GRAYDON CHRISTMAN wrote:
> While teaching my introductory course in Python, I occasionally see
> submissions containing the following two program lines, even before
> I teach about functions and modules:
> 
> if __name__ = '__main__':
> ...  main()
> 
> When I ask about it, I hear things like they got these from other instructors,
> or from other students who learned it from their instructors, or maybe
> from some on-line programming tutorial site.
> 
> I'm all on board with the first of these two lines -- and I teach it myself
> as soon as I get to modules.
> 
> My question is more about the second.
> 
> Do "real" Pythonista's actually define a new function main() instead
> of putting the unit test right there inside the if?

Perhaps not for unit tests, but for scripts, particularly if they come
with a larger package, this is actually fairly common: it allows
setuptools to generate a wrapper script that runs with the Python
version and environment it was installed with.

https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html

Combined with the way "python -m ..." works, this leads to slightly
silly-looking __main__.py modules like this:

https://github.com/jupyter/jupyter_core/blob/master/jupyter_core/__main__.py


> 
> Or am I correct in assuming that this main() is just an artifact from
> people who have programmed in C, C++, or Java for so long that
> they cannot imagine a program without a function named "main"?
> 
> I guess I'm not stuck on that habit, since my programming experiences
> go way back to the old Fortran days....
> 
> 
> Roger Christman
> Pennsylvania State University
> 




More information about the Python-list mailing list