[Python-Dev] Fix import errors to have data

Guido van Rossum guido at python.org
Wed Jul 28 20:41:50 CEST 2004


[Tim]
> When an import of an
> existing module fails for *any* reason, subsequent attempts to import
> the same module succeed.  For example,
> 
> C:\Code>type a.py
> 1/0
> 
> C:\Code>\python23\python.exe
> Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import a
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "a.py", line 1, in ?
>     1/0
> ZeroDivisionError: integer division or modulo by zero
> >>> import a
> >>>
> 
> This is Bad, because an uncaught exception in module initialization
> means the module probably can't fulfill its contract, yet subsequent
> importers get no clue that the module is in a damaged state (until the
> module fails to do its job, which may or may not be obvious when it
> occurs).  A module failing to import because it suffers an ImportError
> itself is once instance of this, but the same applies to a module
> failing to import for any other reason:  in all these cases,
> subsequent imports don't get the exception the initial importer saw,
> they get a module object in an arbitrarily screwed-up state.

So let's try to devise new semantics to cover this and other cases.
One requirement is that mutual imports must work.  Another is that
when "import a" fails once, it must fail again if it is retried after
catching the first failure.

Perhaps it is as simple as deleting the module from sys.modules when
the code in import.c executing the module's body gets any kind of
exception from the execution?  This would seem to be a relatively
small change to PyImport_ExecCodeModuleEx(): unify all the error exits
and there delete the module from sys.modules.  What should it do if
the module already existed (e.g. when used by reload())?  Strawman
answer: leave it there -- the reload() semantics and common use cases
are best served by that.

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


More information about the Python-Dev mailing list