[Python-Dev] Can we limit the effects of module execution to sys.modules? (was Fix import errors to have data)

Barry Warsaw barry at python.org
Wed Jul 28 17:52:35 CEST 2004


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?  

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.

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.

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.

-Barry

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 307 bytes
Desc: This is a digitally signed message part
Url : http://mail.python.org/pipermail/python-dev/attachments/20040728/886a3a5a/attachment-0001.pgp


More information about the Python-Dev mailing list