There are several different ways of running Python programs. Some Python module files are designed to be run directly. These are usually referred to as “programs” or “scripts.” Other Python modules are designed primarily to be imported and used by other programs; these are often called “libraries.” Sometimes we want to create a sort of hybrid module that can be used both as a stand-alone program and as a library that can be imported by other programs.
So far, most of our programs have had a line at the bottom to invoke the main function.
main()
As you know, this is what actually starts a program running. These programs are suitable for
running directly. In a windowing environment, you might run a file by (double-)clicking its icon.
Or you might type a command like python <myfile>.py.
Since Python evaluates the lines of a module during the import process, our current programs
also run when they are imported into either an interactive Python session or into another Python
program. Generally, it is nicer not to have modules run as they are imported. When testing a
program interactively, the usual approach is to first import the module and then call its main (or
some other function) each time we want to run it.
In a program designed to be either imported (without running) or run directly, the call to main
at the bottom must be made conditional. A simple decision should do the trick.
if <condition>:
main()
We just need to figure out a suitable condition.
Whenever a module is imported, Python sets a special variable in the module called __name__
to be the name of the imported module. Here is an example interaction showing what happens
with the math library:
>>> import math
>>> math.__name__
’math’
You can see that, when imported, the __name__ variable inside the math module is assigned the
string ’math’.
However, when Python code is being run directly (not imported), Python sets the value of
__name__ to be ’__main__’. To see this in action, you just need to start a Python shell and look at
the value.
>>> __name__
’__main__’
So, if a module is imported, the code in that module will see a variable called __name__ whose
value is the name of the module. When a file is run directly, the code will see that __name__ has
the value ’__main__’. A module can determine how it is being used by inspecting this variable.
Putting the pieces together, we can change the final lines of our programs to look like this:
if __name__ == ’__main__’:
main()
This guarantees that main will automatically run when the program is invoked directly, but it will
not run if the
This excerpt was taken from section 7.1.3 Example: Conditional Program Execution, Python Porgramming - An Intro to Computer Science 2nd edition - John Zelle.
No comments:
Post a Comment