newbie question

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Nov 27 05:05:30 EST 2008


Asun Friere a écrit :
> 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.

The problem is that you often have more to do in the __main__ section of 
a script than just calling one simple function, and you don't 
necessarily want to pollute the module's namespace with all this code. 
What I usually do is to have a main function called from the __main__ 
section, ie:


# myscript.py
# imports here
# classes and functions def here

def main(argv):
    # parse args
    # do whathever
    return exit_status

if __name__ == "__main__":
     import sys
     sys.exit(main(sys.argv))



More information about the Python-list mailing list