[Python-ideas] only raise ImportError out of imports

Terry Reedy tjreedy at udel.edu
Wed Aug 1 01:09:54 CEST 2012


On 7/31/2012 1:49 AM, Eric Snow wrote:
> 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
> ---------------------------------------------------------

This is really clear to me. SyntaxError in eggs exposed during the 
import call, which obviously failed, as does everything in a traceback.

> ---------------------------------------------------------
> $ 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
> ---------------------------------------------------------

Much worse. Lots of extra noise with the important part buried in the 
middle. I don't see the point of privileging import calls over 
everything else in the call chain. An ImportError should be related to 
an import-specific cause, and SyntaxError is not such. It would be there 
anyway if eggs.py were run directly.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list