PEP 299 – Special __main__() function in modules
- Jeff Epler <jepler at unpythonic.net>
- Standards Track
Many Python modules are also intended to be callable as standalone
scripts. This PEP proposes that a special function called
should serve this purpose.
There should be one simple and universal idiom for invoking a module as a standalone script.
The semi-standard idiom:
if __name__ == '__main__': perform "standalone" functionality
is unclear to programmers of languages like C and C++. It also does not permit invocation of the standalone function when the module is imported. The variant:
if __name__ == '__main__': main_function()
is sometimes seen, but there exists no standard name for the function, and because arguments are taken from sys.argv it is not possible to pass specific arguments without changing the argument list seen by all other modules. (Imagine a threaded Python program, with two threads wishing to invoke the standalone functionality of different modules with different argument lists)
The standard name of the ‘main function’ should be
__main__. When a
module is invoked on the command line, such as:
then the module behaves as though the following lines existed at the end of the module (except that the attribute __sys may not be used or assumed to exist elsewhere in the script):
if globals().has_key("__main__"): import sys as __sys __sys.exit(__main__(__sys.argv))
Other modules may execute:
import mymodule mymodule.__main__(['mymodule', ...])
It is up to
mymodule to document thread-safety issues or other
issues which might restrict use of
__main__. (Other issues might
include use of mutually exclusive GUI modules, non-sharable resources
like hardware devices, reassignment of
modules/main.c, the block near line 385 (after the
PyRun_AnyFileExFlags call) will be changed so that the above code
(or its C equivalent) is executed.
- Should the return value from
__main__be treated as the exit value?
__main__will naturally return
sys.exittranslates into a “success” return code. In those that return a numeric result, it behaves just like the argument to
sys.exit()or the return value from C’s main().
- Should the argument list to
argv, or just the “real” arguments
argvis included for symmetry with
sys.argvand easy transition to the new standard idiom.
In a short discussion on python-dev , two major backwards compatibility problems were brought up and Guido pronounced that he doesn’t like the idea anyway as it’s “not worth the change (in docs, user habits, etc.) and there’s nothing particularly broken.”
This document has been placed in the public domain.
Last modified: 2023-09-09 17:39:29 GMT