[Python-ideas] only raise ImportError out of imports

Eric Snow ericsnowcurrently at gmail.com
Tue Jul 31 07:49:06 CEST 2012


Currently, if module 'eggs' has bad syntax and you import it from
module 'spam', then you will get a SyntaxError in module spam:

---------------------------------------------------------
$ cat > eggs.py << EOF
a +
EOF
$ cat > spam.py << EOF
import eggs
EOF
$ python -c 'import spam'
Traceback (most recent call last):
  File "spam.py", line 2, in <module>
    import eggs
  File "/tmp/eggs.py", line 1
    a +
      ^
SyntaxError: invalid syntax
---------------------------------------------------------

My proposal is that, instead, an error during import always results in
an ImportError.  So in the above example, the error would have been an
ImportError rather than a SyntaxError.  However, rather than ignore
the cause of the import error, we would use exception chaining to save
the SyntaxError.  To get this effect currently would look something
like this:

---------------------------------------------------------
$ cat > spam.py << EOF
try:
    import eggs
except SyntaxError as e:
    raise ImportError("failed to import eggs") from e
EOF
$ python -c 'import spam'
Traceback (most recent call last):
  File "spam.py", line 2, in <module>
    import eggs
  File "/tmp/eggs.py", line 1
    a +
      ^
SyntaxError: invalid syntax

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "spam.py", line 4, in <module>
    raise ImportError("failed to import eggs") from e
ImportError: failed to import eggs
---------------------------------------------------------

With exception chaining the SyntaxError is stored on the ImportError:

---------------------------------------------------------
$ cat > ham.py << EOF
try:
    import spam
except ImportError as e:
    print("cause: {}".format(e.__cause__))
    print("context: {}".format(e.__context__))
EOF
$ python ham.py
cause: invalid syntax (eggs.py, line 1)
context: invalid syntax (eggs.py, line 1)
---------------------------------------------------------

The main benefit of this change would be to isolate errors during
import to the module where they happen.  The main challenge would be
with backward compatibility, so I won't hold my breath to see this in
Python 3.

While all feedback is welcome, I'd particularly like to hear from
those that actually use non-ImportError exceptions that come out of
the import statement.  Thanks!

-eric



More information about the Python-ideas mailing list