Skip to content

Commit

Permalink
Fix a bug in nested() - if one of the sub-context-managers swallows the
Browse files Browse the repository at this point in the history
exception, it should not be propagated up.  With unit tests.
  • Loading branch information
gvanrossum committed Mar 1, 2006
1 parent 6db0e00 commit a9f0687
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ def nested(*contexts):
"""
exits = []
vars = []
exc = (None, None, None)
try:
try:
for context in contexts:
Expand All @@ -103,13 +102,17 @@ def nested(*contexts):
yield vars
except:
exc = sys.exc_info()
else:
exc = (None, None, None)
finally:
while exits:
exit = exits.pop()
try:
exit(*exc)
except:
exc = sys.exc_info()
else:
exc = (None, None, None)
if exc != (None, None, None):
raise

Expand Down
54 changes: 54 additions & 0 deletions Lib/test/test_contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,60 @@ def b():
else:
self.fail("Didn't raise ZeroDivisionError")

def test_nested_b_swallows(self):
@contextmanager
def a():
yield
@contextmanager
def b():
try:
yield
except:
# Swallow the exception
pass
try:
with nested(a(), b()):
1/0
except ZeroDivisionError:
self.fail("Didn't swallow ZeroDivisionError")

def test_nested_break(self):
@contextmanager
def a():
yield
state = 0
while True:
state += 1
with nested(a(), a()):
break
state += 10
self.assertEqual(state, 1)

def test_nested_continue(self):
@contextmanager
def a():
yield
state = 0
while state < 3:
state += 1
with nested(a(), a()):
continue
state += 10
self.assertEqual(state, 3)

def test_nested_return(self):
@contextmanager
def a():
try:
yield
except:
pass
def foo():
with nested(a(), a()):
return 1
return 10
self.assertEqual(foo(), 1)

class ClosingTestCase(unittest.TestCase):

# XXX This needs more work
Expand Down

0 comments on commit a9f0687

Please sign in to comment.