Search code examples
pythoncoding-styleprogram-entry-point

Usage of the function main()?


I am curious whether there is any difference between these two implementations:

def main():
    somecode()

if __name__ == '__main__':
    main()

and alternatively:

if __name__ == '__main__':
    somecode()

except that you may import the function main() from the module


Solution

  • The only practical difference I can think of is something that applied to an answer I gave earlier today here.

    Defining the main logic in its own function main() rather than directly within an if __name__ == '__main__' block makes it easier to handle cases where the program should prematurely end:

    def main():
        ...
        if not continue_program:
            return
    
        ...
        if not continue_program:
            return
    
        ...
    
    if __name__ == '__main__':
        main()
    

    To have gotten the same behaviour directly out of the if block, I'd have needed to nest several conditional bodies (or used something ugly like sys.exit()).