regarding main function

ajikoe at gmail.com ajikoe at gmail.com
Thu Apr 21 03:40:37 EDT 2005


if you run in the same file there is no difference.

Block under "__main__" will be executed if you run that file only but
if you import that file from another file, then if you don't put your
code inside "__main__" your code it will be executed (this is not what
you want).

Example:

You have 1 file called mydll.py
inside mydll you have :

def func1():
   print 'Helo world'

# you want to test your func1()
func1() # when you run you get 'Helo world'

then you have another file called MyCode.py which you like to call
func1(), inside this file you have this code:
import mydll
mydll.func1()

# you hope you get 'Helo World'
# In fact you get :
# 'Helo World'
# 'Helo World'
--------------
This happened because when you import mydll python will execute all
code in mydll including the one you put it for test.

So to overcome this problem if you want to test your code put inside
block __main__, next time you import your mydll it won't execute any
codes inside __main__

Hope this help.

Pujo




More information about the Python-list mailing list