[Tutor] Which is better Practice and why
jeanpierreda at gmail.com
Mon Oct 22 13:54:01 CEST 2012
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
try: raise myprogram.MyError
except MyError: pass
So, in any circumstance where you would use the second one, it's
because you're in a situation where bad things are happening. So use
the first one always. And if there's code in the script you want to
share, put it in a separate module.
More information about the Tutor