[Tutor] What is `if __name__ == "__main__"` for?

Christian Witts cwitts at compuscan.co.za
Fri May 20 13:31:28 CEST 2011


On 2011/05/20 01:29 PM, Christian Witts wrote:
> On 2011/05/20 01:09 PM, Ganesh Kumar wrote:
>> Hi Gurus,
>>
>> I am new python programming.. I see many programs
>> if __name__ == '__main__':
>> when I check __name__ always eq __main__.
>> what purpose use these structure.. please guide me..
>>
>> -Ganesh
>>
>
> If you execute the script directly ie. python script.py the __name__
> will be __main__ but if you import it it's the name of the file.
>
> #first.py
> print __name__
>
> #second.py
> import first
>
> $ python first.py
> __main__
>
> $ python second.py
> first
>

Sorry, forgot to add before sending that the reason I use the `if 
__name__ == '__main__'` structure is so that I can have a standalone 
application that has it's defined entry point and then if I want to 
reuse functions in the application I can import it without having to 
worry that it will execute the entire thing.

-- 
Christian Witts


More information about the Tutor mailing list