Test code
When importing a Python file as a module we are generally interested in variable, object
(class) and function definitions that do not immediately result in any significant program
execution. However, the Python code of an imported module is nonetheless read line by
line by the interpreter and any top-level commands
2
in that file will be executed in the
usual manner. This might not be a problem, but we generally want to import just parts of a
module without running it as if it were the main program. A Python module will often
have a main program so that it can be tested and show examples for its use.
Accordingly, when writing your own Python modules it is commonplace to design them
so that if they are executed directly they run as a main program and use any test code etc.,
but if they are only imported any code that is specific to their main program is not
executed. Usually this is achieved by placing any test code at the bottom of the Python file
and using the special internal variable, __name__. In Python, anything that begins and
ends with a double underscore (‘__’) is part of the language’s internal workings. The
variable __name__ is set at runtime for each module that Python uses in a program. It is
set to the string “__main__” in the main script (which itself may be used as a module in
other programs) that you directly run, and it is set to the module name in all modules that
are then imported, directly or indirectly, from that script.
Thus you often see the following in Python modules:
# implementation code
if __name__ == "__main__":
# test code for implementation code
When the script is run directly then __name__ is set to “__main__” and the test code is
executed, but if the code is imported as a module from somewhere else then __name__ is
set to the module name and so the test code is not executed.
The sys library is often used in this context when your test code might require one or
more arguments, such as a test file name to work with. Suppose you have a function,
wordCount(), that calculates the number of words in a file, and you want to test it. You
could put some test code at the bottom of the module:
def wordCount(fileName):
# implementation
# gives back the word count in fileName
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print('Error: no file name specified')
sys.exit()
fileNames = sys.argv[1:]
for fileName in fileNames:
print(fileName, 'word count =', wordCount(fileName))
Note that sys.argv[0] is the name of the Python script, so the file names are from
position 1 onwards. See
Chapter 5
for discussion of the function definition keyword def
and
Chapter 6
for discussion of command-line arguments sys.argv.
Do'stlaringiz bilan baham: |