newbie question

Asun Friere afriere at yahoo.co.uk
Thu Nov 27 06:17:23 CET 2008


On Nov 27, 6:11 am, Nan <nan.l... at gmail.com> wrote:
> Hello,
>    I just started to use Python. I wrote the following code and
> expected 'main' would be called.
>
> def main():
>   print "hello"
>
> main

Not an answer to your question, but I dislike functions named 'main'
because the situation they occur in would better be dealt with by
exploiting the name of the built-in module '__main__'.  But maybe
that's just me.

However, consider your code rewritten thusly:

def greet () :
    print "hello"

if __name__ == '__main__' :
    greet()

(A more literal translation of your program would be:
if __name__ == '__main__' : print 'hello')

This little trick ensures that greet() will execute if the module is
itself executed as a script, but that it won't if you import it from
elsewhere (ie. another script or the intepreter).

IMHO, it's good practice, wherever you may be tempted to write 'def
main()', intending this to be the glue code for your various functions
etc, instead to test whether the code is running as __main__ as above.



More information about the Python-list mailing list