How about some syntactic sugar for " __name__ == '__main__' "?

Steven D'Aprano steve+comp.lang.python at
Sat Nov 15 11:52:38 CET 2014

John Ladasky wrote:

> I have taught Python to several students over the past few years.  As I
> have worked with my students, I find myself bothered by the programming
> idiom that we use to determine whether a module is being executed or
> merely imported:
>   "if __name__ == '__main__':"
> The use of two dunder tokens -- one as a name in a namespace, and the
> other as a string, is intimidating.  It exposes too much of Python's guts.

The dunders are a tad ugly, but it's actually quite simple and elegant:

* every module has a global variable `__name__` which normally holds 
  the name of the module:

py> import functools
py> functools.__name__
py> import math as foobarbaz
py> foobarbaz.__name__

* When Python imports a module, it sets the global __name__ to that 
  module's actual name (as taken from the file name).

* But when Python runs a file, as in `python2.7 path/to/`, 
  it sets the global __name__ to the magic value '__main__' instead
  of "script".

The consequence is that every module can tell whether it is being run as a
script or not by inspecting the __name__ global. That's all there is to it.


More information about the Python-list mailing list