[Tutor] Which is better Practice and why
steve at pearwood.info
Tue Oct 23 02:42:11 CEST 2012
On 22/10/12 22:54, Devin Jeanpierre 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,
I disagree. See below.
> because it results in the same source file being executed twice,
Not so. That only happens if your module is executed *and* imported
simultaneously. It is perfectly safe to write a module which can be run
as a script, or imported, so long as you don't do both at the same time
from within a single Python process.
Excluding test scripts, I find 145 modules in the Python 2.5 standard
library, and 127 in the Python 3.3 std lib, that use the "if __name__ =="
idiom to be both importable and runnable as a script.
> 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
Then don't do that.
There are very few reasons for importing a module from within itself, and
those reasons are relatively advanced, e.g.:
- circular imports
- some types of introspection
If you do that, and the module directly or indirectly imports itself
while it is running as a script, you may run into trouble. But writing
a dual-purpose module that is usable as an importable module or as a
stand-alone script is not problematic in itself.
> So, in any circumstance where you would use the second one, it's
> because you're in a situation where bad things are happening.
The bad situation is when you have circular imports, including the
case where your module imports itself.
> So use the first one always.
This is contrary to the advice given in the Fine Manual:
More from Python's creator, GvR, and the Effbot:
More information about the Tutor