Intor
__name__
is one such special variable. If the source file is executed as the main program, the interpreter sets the __name__
variable to have a value __main__
. If this file is being imported from another module, __name__
will be set to the module’s name.__name__
is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement
Using
As main srcipt
1 | #!/usr/bin/env python3 |
As a module
Import first_module.py
module as a module
1 | #!/usr/bin/env python3 |
See what’s the different of __name__
Round one
We run first_module.py
directly, it will show us Run first as __main__
, because we check the value of __name__
. Obvisously it’s.
Round two
Running second_module.py
. it shows us Run first as Import first_module
. Here, we’ve known the value of __name__
will be changed. At first script it’s value is ‘main‘ as main level, but it has changed to module name when we import it as a module.
EOF.