Just a quick question about main()

Ned Batchelder ned at nedbatchelder.com
Fri Oct 27 17:17:38 EDT 2017


On 10/27/17 2:05 PM, 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?
>
> 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"?
>
>
There's no need for "if __name__ == '__main__':" for unit tests. You can 
let unittest or pytest discover the tests themselves, and run them.

I often write this clause:

     if __name__ == '__main__':
         sys.exit(main(sys.argv))

Then I can write tests that call main() to be sure it does what I think 
it does.

Or, I can let setuptools entry_points handle that clause for me:

     entry_points={
         'console_scripts': [
             'coverage = coverage.cmdline:main',
         ],
     },


--Ned.



More information about the Python-list mailing list