__main__ — Top-level code environment


In Python, the special name__main__ is used for two important constructs:

  1. the name of the top-level environment of the program, which can bechecked using the__name__=='__main__' expression; and

  2. the__main__.py file in Python packages.

Both of these mechanisms are related to Python modules; how users interact withthem and how they interact with each other. They are explained in detailbelow. If you’re new to Python modules, see the tutorial sectionModules for an introduction.

__name__=='__main__'

When a Python module or package is imported,__name__ is set to themodule’s name. Usually, this is the name of the Python file itself without the.py extension:

>>>importconfigparser>>>configparser.__name__'configparser'

If the file is part of a package,__name__ will also include the parentpackage’s path:

>>>fromconcurrent.futuresimportprocess>>>process.__name__'concurrent.futures.process'

However, if the module is executed in the top-level code environment,its__name__ is set to the string'__main__'.

What is the «top-level code environment»?

__main__ is the name of the environment where top-level code is run.«Top-level code» is the first user-specified Python module that starts running.It’s «top-level» because it imports all other modules that the program needs.Sometimes «top-level code» is called anentry point to the application.

The top-level code environment can be:

  • the scope of an interactive prompt:

    >>>__name__'__main__'
  • the Python module passed to the Python interpreter as a file argument:

    $pythonhelloworld.pyHello, world!
  • the Python module or package passed to the Python interpreter with the-m argument:

    $python-mtarfileusage: tarfile.py [-h] [-v] (...)
  • Python code read by the Python interpreter from standard input:

    $echo"import this"|pythonThe Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit....
  • Python code passed to the Python interpreter with the-c argument:

    $python-c"import this"The Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit....

In each of these situations, the top-level module’s__name__ is set to'__main__'.

As a result, a module can discover whether or not it is running in thetop-level environment by checking its own__name__, which allows a commonidiom for conditionally executing code when the module is not initialized froman import statement:

if__name__=='__main__':# Execute when the module is not initialized from an import statement....

Δείτε επίσης

For a more detailed look at how__name__ is set in all situations, seethe tutorial sectionModules.

Idiomatic Usage

Some modules contain code that is intended for script use only, like parsingcommand-line arguments or fetching data from standard input. If a modulelike this was imported from a different module, for example to unit testit, the script code would unintentionally execute as well.

This is where using theif__name__=='__main__' code block comes inhandy. Code within this block won’t run unless the module is executed in thetop-level environment.

Putting as few statements as possible in the block belowif__name__=='__main__' can improve code clarity and correctness. Most often, a functionnamedmain encapsulates the program’s primary behavior:

# echo.pyimportshleximportsysdefecho(phrase:str)->None:"""A dummy wrapper around print."""# for demonstration purposes, you can imagine that there is some# valuable and reusable logic inside this functionprint(phrase)defmain()->int:"""Echo the input arguments to standard output"""phrase=shlex.join(sys.argv)echo(phrase)return0if__name__=='__main__':sys.exit(main())# next section explains the use of sys.exit

Note that if the module didn’t encapsulate code inside themain functionbut instead put it directly within theif__name__=='__main__' block,thephrase variable would be global to the entire module. This iserror-prone as other functions within the module could be unintentionally usingthe global variable instead of a local name. Amain function solves thisproblem.

Using amain function has the added benefit of theecho function itselfbeing isolated and importable elsewhere. Whenecho.py is imported, theecho andmain functions will be defined, but neither of them will becalled, because__name__!='__main__'.

Packaging Considerations

main functions are often used to create command-line tools by specifyingthem as entry points for console scripts. When this is done,pip inserts the function call into a template script,where the return value ofmain is passed intosys.exit().For example:

sys.exit(main())

Since the call tomain is wrapped insys.exit(), the expectation isthat your function will return some value acceptable as an input tosys.exit(); typically, an integer orNone (which is implicitlyreturned if your function does not have a return statement).

By proactively following this convention ourselves, our module will have thesame behavior when run directly (i.e.pythonecho.py) as it will have ifwe later package it as a console script entry-point in a pip-installablepackage.

In particular, be careful about returning strings from yourmain function.sys.exit() will interpret a string argument as a failure message, soyour program will have an exit code of1, indicating failure, and thestring will be written tosys.stderr. Theecho.py example fromearlier exemplifies using thesys.exit(main()) convention.

Δείτε επίσης

Python Packaging User Guidecontains a collection of tutorials and references on how to distribute andinstall Python packages with modern tools.

__main__.py in Python Packages

If you are not familiar with Python packages, see sectionΠακέταof the tutorial. Most commonly, the__main__.py file is used to providea command-line interface for a package. Consider the following hypotheticalpackage, «bandclass»:

bandclass  ├── __init__.py  ├── __main__.py  └── student.py

__main__.py will be executed when the package itself is invokeddirectly from the command line using the-m flag. For example:

$python-mbandclass

This command will cause__main__.py to run. How you utilize this mechanismwill depend on the nature of the package you are writing, but in thishypothetical case, it might make sense to allow the teacher to search forstudents:

# bandclass/__main__.pyimportsysfrom.studentimportsearch_studentsstudent_name=sys.argv[1]iflen(sys.argv)>=2else''print(f'Found student:{search_students(student_name)}')

Note thatfrom.studentimportsearch_students is an example of a relativeimport. This import style can be used when referencing modules within apackage. For more details, seeIntra-package αναφορές in theModules section of the tutorial.

Idiomatic Usage

The content of__main__.py typically isn’t fenced with anif__name__=='__main__' block. Instead, those files are keptshort and import functions to execute from other modules. Those other modules can then beeasily unit-tested and are properly reusable.

If used, anif__name__=='__main__' block will still work as expectedfor a__main__.py file within a package, because its__name__attribute will include the package’s path if imported:

>>>importasyncio.__main__>>>asyncio.__main__.__name__'asyncio.__main__'

This won’t work for__main__.py files in the root directory of a.zip file though. Hence, for consistency, a minimal__main__.pywithout a__name__ check is preferred.

Δείτε επίσης

Seevenv for an example of a package with a minimal__main__.pyin the standard library. It doesn’t contain aif__name__=='__main__'block. You can invoke it withpython-mvenv[directory].

Seerunpy for more details on the-m flag to theinterpreter executable.

Seezipapp for how to run applications packaged as.zip files. Inthis case Python looks for a__main__.py file in the root directory ofthe archive.

import__main__

Regardless of which module a Python program was started with, other modulesrunning within that same program can import the top-level environment’s scope(namespace) by importing the__main__ module. This doesn’t importa__main__.py file but rather whichever module that received the specialname'__main__'.

Here is an example module that consumes the__main__ namespace:

# namely.pyimport__main__defdid_user_define_their_name():return'my_name'indir(__main__)defprint_user_name():ifnotdid_user_define_their_name():raiseValueError('Define the variable `my_name`!')print(__main__.my_name)

Example usage of this module could be as follows:

# start.pyimportsysfromnamelyimportprint_user_name# my_name = "Dinsdale"defmain():try:print_user_name()exceptValueErrorasve:returnstr(ve)if__name__=="__main__":sys.exit(main())

Now, if we started our program, the result would look like this:

$pythonstart.pyDefine the variable `my_name`!

The exit code of the program would be 1, indicating an error. Uncommenting theline withmy_name="Dinsdale" fixes the program and now it exits withstatus code 0, indicating success:

$pythonstart.pyDinsdale

Note that importing__main__ doesn’t cause any issues with unintentionallyrunning top-level code meant for script use which is put in theif__name__=="__main__" block of thestart module. Why does this work?

Python inserts an empty__main__ module insys.modules atinterpreter startup, and populates it by running top-level code. In our examplethis is thestart module which runs line by line and importsnamely.In turn,namely imports__main__ (which is reallystart). That’s animport cycle! Fortunately, since the partially populated__main__module is present insys.modules, Python passes that tonamely.SeeSpecial considerations for __main__ in theimport system’s reference for details on how this works.

The Python REPL is another example of a «top-level environment», so anythingdefined in the REPL becomes part of the__main__ scope:

>>>importnamely>>>namely.did_user_define_their_name()False>>>namely.print_user_name()Traceback (most recent call last):...ValueError:Define the variable `my_name`!>>>my_name='Jabberwocky'>>>namely.did_user_define_their_name()True>>>namely.print_user_name()Jabberwocky

The__main__ scope is used in the implementation ofpdb andrlcompleter.