bug? context managers vs ImportErrors

Ethan Furman ethan at stoneleaf.us
Thu Aug 19 19:44:19 CEST 2010


Chris Withers wrote:
> Hi All,
> 
> Am I right in thinking this is a bug:
> 
> class MyContextManager:
> 
>     def __enter__(self):
>         pass
> 
>     def __exit__(self,t,e,tb):
>         print type(t),t
>         print type(e),e
> 
> 
> with MyContextManager():
>    import foo.bar.baz
> 
> ...when executed, gives me:
> 
> <type 'type'> <type 'exceptions.ImportError'>
> <type 'str'> No module named foo.bar.baz
> 
> Why is 'e' ending up as a string rather than the ImportError object?
> 
> This is with Python 2.6.5 if that makes a difference...

I don't have an answer, just some more examples across different 
versions/exceptions:

<code>
class MyContextManager:
     def __enter__(self):
         pass
     def __exit__(self,t,e,tb):
         print ('--------')
         print (type(t),t)
         print (type(e),e)
         return True

with MyContextManager():
    import foo.bar.baz
with MyContextManager():
    1/0
with MyContextManager():
    not_here()
</code>

<output>
c:\temp>\python25\python test.py
[0]
--------
(<type 'type'>, <type 'exceptions.ImportError'>)
(<type 'str'>, 'No module named bar.baz')
--------
(<type 'type'>, <type 'exceptions.ZeroDivisionError'>)
(<type 'str'>, 'integer division or modulo by zero')
--------
(<type 'type'>, <type 'exceptions.NameError'>)
(<type 'str'>, "name 'not_here' is not defined")

c:\temp>\python26\python test.py
[0]
--------
(<type 'type'>, <type 'exceptions.ImportError'>)
(<type 'str'>, 'No module named bar.baz')
--------
(<type 'type'>, <type 'exceptions.ZeroDivisionError'>)
(<type 'str'>, 'integer division or modulo by zero')
--------
(<type 'type'>, <type 'exceptions.NameError'>)
(<type 'str'>, "name 'not_here' is not defined")

c:\temp>\python27\python test.py
[0]
--------
(<type 'type'>, <type 'exceptions.ImportError'>)
(<type 'exceptions.ImportError'>, ImportError('No module named bar.baz',))
--------
(<type 'type'>, <type 'exceptions.ZeroDivisionError'>)
(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('integer 
division or modulo by zero',))
--------
(<type 'type'>, <type 'exceptions.NameError'>)
(<type 'exceptions.NameError'>, NameError("name 'not_here' is not 
defined",))

c:\temp>\python31\python test.py
--------
<class 'type'> <class 'SyntaxError'>
<class 'SyntaxError'> invalid syntax (foo.py, line 3)
--------
<class 'type'> <class 'ZeroDivisionError'>
<class 'ZeroDivisionError'> int division or modulo by zero
--------
<class 'type'> <class 'NameError'>
<class 'NameError'> name 'not_here' is not defined

</output>

As an aside, does anyone know why the 2.x versions are printing the [0] 
as the first line?  3.1 does not.



More information about the Python-list mailing list