__name__ == "__main__"
Python 3 creates "special", globally-accessible variables whenever a Python 3 program is being run or an IDLE window open. These variables are instantly recognizable in any program that uses them by their identifiers, since these always consist of two underscore characters followed by a word (or an abbreviation of a word) followed by two more underscores. Of particular interest in CISC 121 are the __doc__
string variables that are created for all modules and functions, and the __name__
string variables that are created for all modules. This article describes the latter.
At the bottom of any module we build for the course, we should include code that tests each of the functions defined in the module. This code should only ever execute while the module is under development. The __name__
variable's value is context dependent, and this helps us to stop test code from executing when a module is imported by another module. The rules for determining the value of a module's __name__
variable are as follows:
__name__
variable has the string value "__main__"
. This is also the case if the module is being run from a Terminal or Command Prompt window as a standalone Python 3 program.import
ed by another module so that its functions may be executed indirectly within that other module, then the imported module's __name__
variable's value is the same as the imported module's file name minus the ".py" extension.print("__name__ from my_module: " + __name__ + ".")
__name__ from my_module: __main__.
import my_module
__name__ from my_module: my_module.
print("__name__ from my_program: " + __name__ + ".")
__name__ from my_module: my_module. __name__ from my_program: __main__.
So, executed by itself, my_module.py's __name__
variable has the string value "__main__"
, but when it is executed indirectly, by way of an import into another module, its __name__
becomes "my_module"
, and the string "__main__"
is now assigned to the __name__
variable of the executing program (in this case, to my_program.py).
Now we'll see how the value of the __name__
variable can be used to execute code selectively in a module depending on whether that module is being run as a standalone program or as an import into another module.
if __name__ == "__main__": print("Executing directly, not by way of an import.") else: print("Executing indirectly, by way of an import.")
Executing directly, not by way of an import.
import my_other_module
Executing indirectly, by way of an import.
Note that if you had left the else:
code out of my_other_module.py, the output from my_program.py would have been nothing at all. In other words, any code you attach to the conditional statement
if __name__ == "__main__":
in a module is only ever executed when the module is being executed directly. For a module designed to be used as an import for other modules, that becomes the perfect place to put testing code for the module.