Python's equivalent to Main calling program and subprograms

Tim Harig usernet at ilthio.net
Wed Dec 1 14:13:54 EST 2010


> On Wed, Dec 1, 2010 at 9:08 AM, m b <snert at hotmail.se> wrote:
>>> > if __name__ == "__main__":
>>> > main()
>>
>> What does this mean?

It is a Python idiom and a good practice.  Strictly speaking it is
unnecessary.  Python doesn't recognize any functional initialization
vector other then the start of the file.  When Python loads a module,
it executes anything it finds in the module scope (Anything not in the
body of a class or function declaration).  Using a main function is just
a convention.  You could just place all of your main level code in the
module scope:

def Subprogram1():
	# code
def Subprogram2():
	# code
def Subprogram3():
	# code

# main code

or equivilantly, always execute main():

def Subprogram1():
	# code
def Subprogram2():
	# code
def Subprogram3():
	# code
def main():
	# main code
main()

Both are valid from Python's point of view.

The 'if __name__ == "__main__":' idiom is used, because it allows the
module to be loaded without running main().  This is useful if you wanted
to use Subprogram2() from another program.  Even if you don't forsee using
any of the subprograms (functions to Python), this can be useful when
writing test code as you can import the program as a module to test its
classes or functions separately.



More information about the Python-list mailing list