Project-wide variable...

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jun 23 22:11:37 EDT 2011


On Thu, 23 Jun 2011 19:01:59 -0700, Gnarlodious wrote:

> On Jun 23, 12:10 pm, Terry Reedy wrote:
> 
>> from test import ftest,itest
>>
>> def test_main():
>>
>> if __name__ == '__main__':
>>      test_main()
> 
> I don't understand this. Can you explain, or refer me to some
> documentation?

What part don't you understand?

This is Terry's template. It's not meant to work as-is, he has to fill in 
the details, such as what test_main() actually does.

The "if __name__ == '__main__'" idiom is a common way of making a Python 
script. When you import a module, Python automatically adds a global to 
it called __name__, and sets it to the name of the module. E.g.:

>>> import math
>>> math.__name__
'math'

When you run a module as a script, Python sets the __name__ to '__main__' 
instead. So this is a (slightly hacky) way of distinguishing code that 
runs when the module is imported from code that runs on execution.


-- 
Steven



More information about the Python-list mailing list