There are two ways in which a Python source file can execute. The import statement executes code in its own namespace as a library module. However, code might also execute as the main program or script. This occurs when you supply the program as the script name to the interpreter:
% python spam.py
Each module defines a variable, __name__ , that contains the module name. Programs can examine this variable to determine the module in which they're executing. The top-level module of the interpreter is named__main__. Programs specified on the command line or entered interactively run inside the__main__module. Sometimes a program may alter its behavior, depending on whether it has been imported as a module or is running in__main__. For example, a module may include some testing code that is executed if the module is used as the main program but which is not executed if the module is simply imported by another module. This can be done as follows:
# Check if running as a program if__name__== '__main__':
# Yes statements else:
# No, I must have been imported as a module statements
It is common practice for source files intended for use as libraries to use this technique for including optional testing or example code. For example, if you're developing a
Was this article helpful?