[Tutor] Which is better Practice and why
jeanpierreda at gmail.com
Tue Oct 23 02:28:27 CEST 2012
On Mon, Oct 22, 2012 at 9:23 AM, Walter Prins <wprins at gmail.com> wrote:
> 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
> its use?
It's that your module was imported, while it was executed as a script.
It's fairly common for modules to import each other for various
reasons. Especially if one module is executable, it might do
"circular" imports for the purposes of its execution (tests or what
have you), and these break because the reverse part of the "circle"
actually create a new module rather than doing a circular import.
This kind of behavior is pretty much impossible if your scripts are
scripts, and your modules are modules. The only downside is that you
have to import the code you use in your scripts.
More information about the Tutor