29.4.__main__ — Top-level script environment


'__main__' is the name of the scope in which top-level code executes.A module’s __name__ is set equal to'__main__' when read fromstandard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope bychecking its own__name__, which allows a common idiom for conditionallyexecuting code in a module when it is run as a script or withpython-m but not when it is imported:

if__name__=="__main__":# execute only if run as a scriptmain()

For a package, the same effect can be achieved by including a__main__.py module, the contents of which will be executed when themodule is run with-m.