[Tutor] Reviewing scripts & main statements in function

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jan 16 14:13:19 EST 2004



On Thu, 15 Jan 2004, Barnaby Scott wrote:

> Thanks very much for that. I was interested to see your comments, and am
> as pleased to receive stylistic help as much as any other kind.
>
> Can I ask one other question, which may have wider relevance for
> others?:
>
> You (or another contributor) put the main statement
> block into a function and then called it with the line
>
> if __name__ == '__main__': main()
>
> I have seen this before - is it universally good practice? What about
> scripts that were only ever intended to be run standalone?


Hi Barnaby,



This convention also works really nicely even with standalone programs.


Let me give a concrete example:

###
def main():
    print "The square of 42 is", square(42)

def square(x):
    return x * x

if __name__ == '__main__':
    main()
###


This code works because by the time the main() function is actually
called, square() is known to the system.


If we don't use the 'if __name__ == "__main__": ...' convention, and just
try it:


###
print "The square of 42 is", square(42)

def square(x):
    return x * x
###


we will find that Python doesn't like this at all, because as it executes
the first line of the program,

    print "The square of 42 is", square(42)

it doesn't yet know what 'square()' is.  To make this work without a real
main() function, we're forced to rearrange things so that the function
definitions are in place before we call them:


###
def square(x):
    return x * x

print "The square of 42 is", square(42)
###



So we can benefit from the 'if __name__ ...' convention, even if we're not
module writers: the convention allows us to push the main functionality of
our program to the very top of our source file, where it'll be noticed
more easily.


I hope this helps!




More information about the Tutor mailing list