Total newbie question: Best practice

Pedro Henrique G. Souto pedro.h.souto at gmail.com
Wed Nov 30 06:36:15 EST 2011


On 30/11/2011 06:50, Shambhu Rajak wrote:
> Collins Congratulations for your first step into Python Programming.
> You can call them script or programs(not necessarily but depends on what your coding for).
> Yaa..it's always a good practice to call it through main(), but it doesn't really matter you
> can call the method in way....
>
> Regards,
> Shambhu
>
> -----Original Message-----
> From: Colin Higwell [mailto:colinh at somewhere.invalid]
> Sent: 30/11/2011 1:37 AM
> To: python-list at python.org
> Subject: Total newbie question: Best practice
>
> Hi,
>
> I am just starting to learn Python (I have been at it only a few hours),
> so please bear with me. I have a few very small scripts (do you call them
> scripts or programs?) which work properly, and produce the results
> intended.
>
> However, they are monolithic in nature; i.e. they begin at the beginning
> and finish at the end. Having done a little reading, I note that it seems
> to be quite common to have a function main() at the start (which in turn
> calls other functions as appropriate), and then to call main() to do the
> work.
>
> Is that standard best practice?
>
> Thanks

Congratulations on becoming a Pythonist!

Like Shambhu said, it doesn't matter where do you put the code, but is 
interesting to have a main() function when you have a program, and you 
want to differentiate if it is running directly (i.e. python program.py) 
or if it is running as a  module, imported by other program (i.e. import 
program).

To do so, you do this:

main():
     # blablabla

if __name__ == '__main__':
     main()


If the program is running directly, the variable __name__ will be 
'__main__', if not, __name__ will be the name of the module ('program', 
in this case).

Att;
Pedro



More information about the Python-list mailing list