bug? context managers vs ImportErrors
Peter Otten
__peter__ at web.de
Thu Aug 19 14:08:13 EDT 2010
Ethan Furman wrote:
> 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.
If reading the error messages carefully doesn't help scroll down for a
hint;)
Look into foo.py
More information about the Python-list
mailing list