[Tutor] Which is better Practice and why
wprins at gmail.com
Mon Oct 22 15:23:32 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:
>> 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.
> class MyError(Exception): pass
> import myprogram
> try: raise myprogram.MyError
> except MyError: pass
Why would you do this though? Is the source of the problem not really
that you're importing a module inside itself? Why would you generally
want to do this? Furthermore the 'if __name__ == "__main__"' idiom is
explicitly part of Python and generally well accepted (so it seems to
me at least), so the above seems like a fairly esoteric objection to
More information about the Tutor