Skip to content
Search

Python: main

lastmod 2020-12-13created 2020-12-131 edits

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

A module can check whether it is running in the main scope by checking its own __name__. This allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m, but not when it is imported:

if __name__ == "__main__":
    # execute only if run as a script
    main()

For a package, the same effect can be achieved by including a __main__.py module. The contents of that module are executed when the module is run with -m.

See also

Favorite site

author Zer0 sitemap