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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Nov 15 05:52:38 EST 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__
'functools'
py> import math as foobarbaz
py> foobarbaz.__name__
'math'


* 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/script.py`, 
  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.





-- 
Steven




More information about the Python-list mailing list