Allow multiple context managers in one with statement, as proposed

in http://codereview.appspot.com/53094 and accepted by Guido.

The construct is transformed into multiple With AST nodes so that
there should be no problems with the semantics.
This commit is contained in:
Georg Brandl 2009-05-25 21:02:56 +00:00
parent 04516611e7
commit 944f684ce6
11 changed files with 216 additions and 71 deletions

View file

@ -165,6 +165,27 @@ class CompilerTest(unittest.TestCase):
exec c in dct
self.assertEquals(dct.get('result'), 1)
def testWithMult(self):
events = []
class Ctx:
def __init__(self, n):
self.n = n
def __enter__(self):
events.append(self.n)
def __exit__(self, *args):
pass
c = compiler.compile('from __future__ import with_statement\n'
'def f():\n'
' with Ctx(1) as tc, Ctx(2) as tc2:\n'
' return 1\n'
'result = f()',
'<string>',
'exec' )
dct = {'Ctx': Ctx}
exec c in dct
self.assertEquals(dct.get('result'), 1)
self.assertEquals(events, [1, 2])
def testGlobal(self):
code = compiler.compile('global x\nx=1', '<string>', 'exec')
d1 = {'__builtins__': {}}