[Python-ideas] breaking out of module execution

Jim Jewett jimjjewett at gmail.com
Thu Apr 26 02:27:54 CEST 2012

On Wed, Apr 25, 2012 at 5:41 AM, M.-A. Lemburg <mal at egenix.com> wrote:
> Nick Coghlan wrote:
>> On Wed, Apr 25, 2012 at 10:55 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> IMO, defining things twice in the same module is not a very Pythonic
> way of designing Python software.

Agreed, which is one problem with accelerator modules.

> Left aside the resource leakage, it also makes if difficult to find
> the implementation that actually gets used,

Agreed, which is another problem with accelerator modules.

> bypasses "explicit is better than implicit",

Agreed, which is is another problem with
import * from accelerator

So far, these reasons have been saying "Don't do that if you can help
it", and if you do it anyhow, making the code stick out is better than

(That said, making it stick out by having top-level definitions that
are *not* at the far left is ... unfortunate.)

> and it doesn't address possible side-effects
> of the definitions that you eventually override at the end of the
> module.

That is a real problem, but the answer is to be more explicit.

    from _foo import A
except ImportError
    ...  # define exactly A, as it will be needed


except NameError:
    ...  # define exactly A, as it will be needed

or even create a wrapper that imports or defines your object the first
time it is called...

> Python is normally written with a top-to-bottom view in mind, where
> you don't expect things to suddenly change near the end.

Actually, I tend to (wrongly) view the module-level code as fixed
declarations rather than commands, so that leaving a name undefined or
defining it conditionally is just as bad.

Having an alternative definition in the same location is less of a
problem.  I have learned to look for import * at the beginning and end
of a module,  but more special cases would not be helpful.


More information about the Python-ideas mailing list