Every Python module includes a set of magic variables which can be seen by using the dir() function after importing the module. One of these magic variables, "__name__", stores either the name of that module or the string value "__main__". If the module is being run by itself than we have __name__ = '__main__'. However, whenever the module is imported from another location than the magic variable __name__ stores the name of that module. This can be confirmed by running the print command on the variable:
Code:
>>>print __name__
__main__
Code:
>>>import math
>>>print math.__name__
math
This property is very useful while writing and testing modules that could potentially be imported. The following piece of code is taken from the Marakana Python Training. It demonstrates how this magic variable can be used to test a module you wrote in a way that is not seen from outside of the code:
Code:
#!/usr/bin/env python
"""Unwraps and prints out a 2-D sequence.
Note that the testing only happens when this module
is the "__main__" module.
"""
def PrintTable(table):
"""Prints out a 2-D sequence"""
for row in table:
for column in row:
print column,
print
print
def Test():
tests = (["Hi", "Hola"],
(('H','i'), ('H','o','l','a')),
[["Hi"], ["Hola"]]
)
for test in tests:
print test
PrintTable(test)
if __name__ == '__main__':
Test()
"""
$ tables.py
['Hi', 'Hola']
H i
H o l a
(('H', 'i'), ('H', 'o', 'l', 'a'))
H i
H o l a
[['Hi'], ['Hola']]
Hi
Hola
$ """
The line "if __name__ == '__main__':" checks if we are running this module by itself or importing it. The condition within the if statement evaluates to 'True' if we run the module by itself and the test code given in the function Test() is run. This is demontrated below by running this code in the interpreter:
Code:
['Hi', 'Hola']
H i
H o l a
(('H', 'i'), ('H', 'o', 'l', 'a'))
H i
H o l a
[['Hi'], ['Hola']]
Hi
Hola
However, when the module is imported, the condition evaluates to 'False' and the module is imported without any of the test code being run:
Code:
>>>import tables
>>>
Edited one time. Last edit by Ismail Ceylan on Jun 13, 2010 at 11:17:35 PM (about 2 years ago).