Search notes:
Python: __name__
The predefined global
variable __name__
is a
string whose value corresponds to the module where it is evaluated.
If the source code that contains
__name__
is executed as a script (rather than
imported), the value of
__name__
is
__main__
.
This behavior can be demonstrated with the following simple Python source file (tq84.py
):
if __name__ == '__main__':
print('This source is run as a script')
else:
print('This source was imported, __main__ = {}'.format(__name__))
This script prints This source is run as a script if it is executed from the command line like so:
$ python tq84.py
Conversely, it prints This source was imported, __main__ = tq84 if it is imported from another script like so:
import tq84
See also
__name__
is one of the names that is present in the top level scope (
__name__ == '__main__'
) as returned by
dir()
.