CISC 121

__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:

By way of demonstration, do the following in IDLE:

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.

  1. Create a new file.
  2. Type the following, with indents as shown, into the new file:
    if __name__ == "__main__":
        print("Executing directly, not by way of an import.")
    else:
        print("Executing indirectly, by way of an import.")
  3. Save the file using the file name my_other_module.py. Again, it is important that this new file is saved in the same folder on your computer as the previous two files.
  4. Run the new module. Its output should be this:
    Executing directly, not by way of an import.
  5. Return to the IDLE window containing the code for my_program.py and edit it to look like this:
    import my_other_module
  6. Save the file and run it. You should see this output appear:
    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.