if __name__ == '__main__':

7stud bbxx789_05ss at yahoo.com
Thu Mar 20 18:32:06 CET 2008


On Mar 20, 10:21 am, "Simon Brunning" <si... at brunningonline.net>
wrote:
> On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde <bbko... at gmail.com> wrote:
> > Hi,
> > I am new to the python and not getting meaning of following line,
>
> > if __name__ == '__main__':
> >       main()
>

The if statement is used to skip the code after the if statement in
certain situations.  If that if statement is in a file named test1.py,
and you issue this command:

$ python test1.py

then the code after the if statement will execute.  That's because
python assigns the string '__main__' to the variable __name__ when the
program starts

However, if you do this:

-------
#test1.py
def my_func(num):
    print num * 2


if __name__ == "__main__":
    print "Testing my func:", my_func(10)

--------

#test2.py
import test1

test1.my_func(5)

-------

...and you issue the command:

$python test2.py

Then the code after the if statement in test1.py will not execute.



More information about the Python-list mailing list