Just a quick question about main()

Chris Angelico rosuav at gmail.com
Fri Oct 27 14:28:06 EDT 2017


On Sat, Oct 28, 2017 at 5:23 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Oct 28, 2017 at 5:05 AM, ROGER GRAYDON CHRISTMAN <dvl at psu.edu> 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"?
>
> If it's JUST for unit tests, I'd expect no main(), but instead to have
> it go straight into unittest.main(). IMO, the construct you show there
> implies three things:
>
> 1) This module is intended to be run from the command line
> 2) This module is intended to be imported by other modules
> 3) If imported by another module, this can also be invoked as if it
> were the top-level app.
>
> If #1 is not true, you don't need any sort of "if name is main" code,
> because that's not the point. If #2 is not true, you don't need to
> guard your main routine, because the condition will always be true.
> (Note that external unit tests count as

Whoops, premature send. External unit tests count as importing this
from another module, so that satisfies that.

But if #3 is not the case, then you might well have an "if name is
main" block, but there's no point having "def main()". Unless you
would import the module *and then call main*, don't bother having a
main(). Just have whatever other code you need, right there in the
'if' block. One thing I'll often do, for instance, is to have a pure
function that can be imported, and then do some simple command-line
parsing:

def spamify(ham, eggs, sausages):
    """Spamify stuff"""

if __name__ == "__main__":
    import sys
    _, ham, eggs, sausages, *_ = sys.argv + ["", "", ""]
    print(spamify(ham, eggs, sausages))

No point having a main() to do that; the real work is in the
importable function, and for command-line usage, it simply calls that
function and prints the result.

ChrisA



More information about the Python-list mailing list