watch this The wheels are turning, slowly turning. home
How to define a main entry point into a Python program 2009-07-20

Here’s a common pattern you’ll find in many Python programs:

import some.modules

def ineSomeFunctions():
    pass

class Whatever:
    pass

def main():
    ineSomeFunctions(Whatever())


if __name__ == '__main__':
    main()



This works because the global __name__ is set to “__main__” when evaluating the code in the file invoked on the command line. This has a problem, though. It also puts all of those functions and classes into a module named “__main__”. Sometimes this isn’t an issue, but usually it will become one.

So what should you do instead? This:

if __name__ == '__main__':
    import mymodule
    raise SystemExit(mymodule.main())

import some.modules

def ineSomeFunctions():
    pass

class Whatever:
    pass

def main():
    ineSomeFunctions(Whatever())



It’s probably possible to do even better than this, but even this simple change buys a lot - suddenly no more __main__ wackiness. So, do it this way!