bug? context managers vs ImportErrors

C

Chris Withers

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

Chris
 
S

Steven D'Aprano

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?

Because e is the exception value, not an exception instance. In other
words, if you call t(e) you will get the instance you're expecting.

See the docs:

http://docs.python.org/library/stdtypes.html#contextmanager.__exit__

The three arguments exc_type, exc_value, exc_tb are the same three
arguments you can pass to the raise statement:

http://docs.python.org/reference/simple_stmts.html#the-raise-statement

(BTW, I'm not suggesting you should do that from inside the __exit__
method.)

So, no, this is not a bug.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top