[Tutor] Which is better Practice and why
Oscar Benjamin
oscar.j.benjamin at gmail.com
Mon Oct 22 15:35:06 CEST 2012
On 22 October 2012 12:54, Devin Jeanpierre <jeanpierreda at gmail.com> wrote:
> On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:
Hi Devin, your context was missing the crucial part showing the "2nd one":
>> they call the main program by simply calling the main function. I've also
>> seen a more complcated:
>>
>> if __name__ == '__main__':
>> main()
>> the 2nd one usually includes a lot more code then i showed. can you please
>> tell me why different methods are used to access the main code? is it just
>> preference or is one way actually better coding practice?
>
> The second one is used if your importable modules are also scripts
> that can be executed.
>
> That's a bad idea, because it results in the same source file being
> executed twice, producing distinct classes that break typechecking. If
> you have "myprogram.py" containing the following source code, and
> execute it as a program, it will terminate with an uncaught MyError.
There is nothing wrong with having a script that can also be imported
(or a module that can also be executed). I do this often, particularly
when I have a number of related scripts in the same folder as one
another.
Python allows a .py file to represent a script or a module. Python
itself maintains no formal distinction between scripts and modules.
Adding if __name__ == "__main__" allows your script/module to
determine whether it is being executed or imported and do different
things in each case.
One case where this is good is to add a test suite to a module. For
example my module defines some functions that can be imported by other
modules. It also defines some code to test that the functions it
defines are working properly. I don't want to run the tests every time
I import the module but I can run them conveniently if I put them in a
__name__ == "__main__" block and then execute the module as a script
every now and then. Both the unittest and doctest modules supply
functions specifically for use in this way.
Another common case is that your module defines some functions that
are of general use but you also make it possible to run the module as
a script in order to perform some of the most common operations that
your module performs. There are several examples in the Python
standard library that do this for example pdb and cProfile.
It is also sometimes useful to define a number of scripts that are in
the same directory but share some code by importing one another. You
need the if __name__ =="__main__" block for this.
The problem that Devin is referring to only happens in certain odd
situations where the script that you run ends up importing itself
(perhaps indirectly). I have never personally had that problem though.
Oscar
More information about the Tutor
mailing list