mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
gh-108113: Make it possible to create an optimized AST (#108154)
This commit is contained in:
parent
47022a079e
commit
10a91d7e98
10 changed files with 124 additions and 14 deletions
|
@ -369,16 +369,17 @@ class BuiltinTest(unittest.TestCase):
|
|||
(1, False, 'doc', False, False),
|
||||
(2, False, None, False, False)]
|
||||
for optval, *expected in values:
|
||||
with self.subTest(optval=optval):
|
||||
# test both direct compilation and compilation via AST
|
||||
codeobjs = []
|
||||
codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
|
||||
tree = ast.parse(codestr)
|
||||
codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
|
||||
for code in codeobjs:
|
||||
ns = {}
|
||||
exec(code, ns)
|
||||
rv = ns['f']()
|
||||
self.assertEqual(rv, tuple(expected))
|
||||
codeobjs = []
|
||||
codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
|
||||
tree = ast.parse(codestr)
|
||||
codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
|
||||
for code in codeobjs:
|
||||
ns = {}
|
||||
exec(code, ns)
|
||||
rv = ns['f']()
|
||||
self.assertEqual(rv, tuple(expected))
|
||||
|
||||
def test_compile_top_level_await_no_coro(self):
|
||||
"""Make sure top level non-await codes get the correct coroutine flags"""
|
||||
|
@ -517,6 +518,28 @@ class BuiltinTest(unittest.TestCase):
|
|||
exec(co, glob)
|
||||
self.assertEqual(type(glob['ticker']()), AsyncGeneratorType)
|
||||
|
||||
def test_compile_ast(self):
|
||||
args = ("a*(1+2)", "f.py", "exec")
|
||||
raw = compile(*args, flags = ast.PyCF_ONLY_AST).body[0]
|
||||
opt = compile(*args, flags = ast.PyCF_OPTIMIZED_AST).body[0]
|
||||
|
||||
for tree in (raw, opt):
|
||||
self.assertIsInstance(tree.value, ast.BinOp)
|
||||
self.assertIsInstance(tree.value.op, ast.Mult)
|
||||
self.assertIsInstance(tree.value.left, ast.Name)
|
||||
self.assertEqual(tree.value.left.id, 'a')
|
||||
|
||||
raw_right = raw.value.right # expect BinOp(1, '+', 2)
|
||||
self.assertIsInstance(raw_right, ast.BinOp)
|
||||
self.assertIsInstance(raw_right.left, ast.Constant)
|
||||
self.assertEqual(raw_right.left.value, 1)
|
||||
self.assertIsInstance(raw_right.right, ast.Constant)
|
||||
self.assertEqual(raw_right.right.value, 2)
|
||||
|
||||
opt_right = opt.value.right # expect Constant(3)
|
||||
self.assertIsInstance(opt_right, ast.Constant)
|
||||
self.assertEqual(opt_right.value, 3)
|
||||
|
||||
def test_delattr(self):
|
||||
sys.spam = 1
|
||||
delattr(sys, 'spam')
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue