[Tutor] Which is better Practice and why

Joel Goldstick joel.goldstick at gmail.com
Mon Oct 22 13:58:51 CEST 2012

On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:
> In many of the tutorial examples ive come across, the main code's program is
> never at the top level, but always in a function of some sort. i understand
> why but, there is always a different way used to access the main code, i
> want to know which is the best.
> main()
>      main's code
> #top level
> main()
> they call the main program by simply calling the main function. I've also
> seen a more complcated:
> if __name__ == '__main__':
>     main()
Every module in python has a name.  You have probably seen code like this:

    import os
    import sys

os and sys are modules and their names are 'os' and 'sys'

When you write your own program in a file 'my_code.py' and then run it
by typing:

    python my_code.py

The name of your program is '__main__'

So when you write:

  if __name__ == '__main__':
    <your code here>

The code will only run when  you run the file directly.  Many times,
the functions in your file could be used in other programs.  In that
case you might have a file called my_new_code.py
In my_new_code.py you could import the other file so you could use its
functions.  Like this:

    import my_code

When you import the file, it is not the __main__ code.  Its name will
be my_code.  And so the code you have in the part I marked <your code
here> will never run.  It only runs when you run the file directly.

Joel Goldstick

More information about the Tutor mailing list