[Python-Dev] Fix import errors to have data

Guido van Rossum guido at python.org
Wed Jul 28 18:53:14 CEST 2004

> A possible way to make this work is to have an exception that is raised
> of a module can't be found *and* if no module code has executed. <shrug>

Huh?  That would only make a difference if the *first* import in a
module failed.

> From: Barry Warsaw <barry at python.org>
> On Wed, 2004-07-28 at 06:56, Jim Fulton wrote:
> > Do you think it's practical to limit the effects of module import to
> > sys.modules, even by convention?  Could we say that it is a bug for
> > code executed during module import to mutate other modules, including
> > mutating objects contained in those other modules?

I'm uncomfortable with that; while it's indeed conventional for
modules to mostly define classes and functions (and constants and
global variables and ...), there are many other useful things one
could do at module level, and I hesitate to declare those in any way,
shape or sense frowned upon.  You can have stricter rules within a
project, of course, but I don't want to make this part of the general
Python culture; your concerns are mostly relevant only for very large

[Barry again]
> It's fairly common practice to execute code at module scope, as a
> side-effect of importation.  I've always been uncomfortable with that
> idiom for many of the reasons you point out, but it is a darn convenient
> place to do such things.

Um, importing a module is executing code.  Defining a class or method
is executing code.  Defining a module-global (or class) constant is
executing code.  Initializing a module-global variable.  Etc.  Where
do you draw the line?

> I wonder if we can't define a protocol for executing code at module
> scope, but only if the module is successfully imported.  The idea is
> that we'd define something like an __init__() for modules that would
> only get executed after the module was imported, and if there were any
> failures in importing, it wouldn't get called.

I don't think this can reasonably done.  It would have to contain
everything that's currently at module scope, which would defeat the

> We'd have to handle chained imports though.  I haven't thought through
> all the implications of that but I can imagine it will get messy.  You
> probably don't want to execute any __init__()'s until all imports are
> finished, you probably want to execute them in the order you saw them,
> and you don't want any exceptions raised in __init__()'s to be deemed an
> ImportError worthy of sys.modules deletion.
> Maybe this isn't feasible, but I throw it out there as a thought.

Let me throw it out again.  You'll agree after you've had your
coffee. :-)

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list