blob: 7df577985de1775813626f10aed4a2926ebebd03 [file] [log] [blame]
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001import ast
2import dis
Benjamin Peterson832bfe22011-08-09 16:15:04 -05003import os
4import sys
5import unittest
Miss Islington (bot)522a3942019-08-26 00:43:33 -07006import warnings
Benjamin Peterson9ed37432012-07-08 11:13:36 -07007import weakref
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00008from textwrap import dedent
Benjamin Peterson9ed37432012-07-08 11:13:36 -07009
10from test import support
Tim Peters400cbc32006-02-28 18:44:41 +000011
12def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +000013 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +000014 return t
15 elif isinstance(t, list):
16 return [to_tuple(e) for e in t]
17 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000018 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
19 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000020 if t._fields is None:
21 return tuple(result)
22 for f in t._fields:
23 result.append(to_tuple(getattr(t, f)))
24 return tuple(result)
25
Neal Norwitzee9b10a2008-03-31 05:29:39 +000026
Tim Peters400cbc32006-02-28 18:44:41 +000027# These tests are compiled through "exec"
Ezio Melotti85a86292013-08-17 16:57:41 +030028# There should be at least one test per statement
Tim Peters400cbc32006-02-28 18:44:41 +000029exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050030 # None
31 "None",
INADA Naokicb41b272017-02-23 00:31:59 +090032 # Module docstring
33 "'module docstring'",
Tim Peters400cbc32006-02-28 18:44:41 +000034 # FunctionDef
35 "def f(): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090036 # FunctionDef with docstring
37 "def f(): 'function docstring'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050038 # FunctionDef with arg
39 "def f(a): pass",
40 # FunctionDef with arg and default value
41 "def f(a=0): pass",
42 # FunctionDef with varargs
43 "def f(*args): pass",
44 # FunctionDef with kwargs
45 "def f(**kwargs): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090046 # FunctionDef with all kind of args and docstring
47 "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **kwargs): 'doc for f()'",
Tim Peters400cbc32006-02-28 18:44:41 +000048 # ClassDef
49 "class C:pass",
INADA Naokicb41b272017-02-23 00:31:59 +090050 # ClassDef with docstring
51 "class C: 'docstring for class C'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050052 # ClassDef, new style class
53 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000054 # Return
55 "def f():return 1",
56 # Delete
57 "del v",
58 # Assign
59 "v = 1",
Serhiy Storchakab619b092018-11-27 09:40:29 +020060 "a,b = c",
61 "(a,b) = c",
62 "[a,b] = c",
Tim Peters400cbc32006-02-28 18:44:41 +000063 # AugAssign
64 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000065 # For
66 "for v in v:pass",
67 # While
68 "while v:pass",
69 # If
70 "if v:pass",
Miss Islington (bot)3b18b172019-12-13 08:21:54 -080071 # If-Elif
72 "if a:\n pass\nelif b:\n pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050073 # With
74 "with x as y: pass",
75 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000076 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000077 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000078 # TryExcept
79 "try:\n pass\nexcept Exception:\n pass",
80 # TryFinally
81 "try:\n pass\nfinally:\n pass",
82 # Assert
83 "assert v",
84 # Import
85 "import sys",
86 # ImportFrom
87 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000088 # Global
89 "global v",
90 # Expr
91 "1",
92 # Pass,
93 "pass",
94 # Break
Yury Selivanovb3d53132015-09-01 16:10:49 -040095 "for v in v:break",
Tim Peters400cbc32006-02-28 18:44:41 +000096 # Continue
Yury Selivanovb3d53132015-09-01 16:10:49 -040097 "for v in v:continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000098 # for statements with naked tuples (see http://bugs.python.org/issue6704)
99 "for a,b in c: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200100 "for (a,b) in c: pass",
101 "for [a,b] in c: pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500102 # Multiline generator expression (test for .lineno & .col_offset)
103 """(
104 (
105 Aa
106 ,
107 Bb
108 )
109 for
110 Aa
111 ,
112 Bb in Cc
113 )""",
114 # dictcomp
115 "{a : b for w in x for m in p if g}",
116 # dictcomp with naked tuple
117 "{a : b for v,w in x}",
118 # setcomp
119 "{r for l in x if g}",
120 # setcomp with naked tuple
121 "{r for l,m in x}",
Yury Selivanov75445082015-05-11 22:57:16 -0400122 # AsyncFunctionDef
INADA Naokicb41b272017-02-23 00:31:59 +0900123 "async def f():\n 'async function'\n await something()",
Yury Selivanov75445082015-05-11 22:57:16 -0400124 # AsyncFor
125 "async def f():\n async for e in i: 1\n else: 2",
126 # AsyncWith
127 "async def f():\n async with a as b: 1",
Yury Selivanovb3d53132015-09-01 16:10:49 -0400128 # PEP 448: Additional Unpacking Generalizations
129 "{**{1:2}, 2:3}",
130 "{*{1, 2}, 3}",
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700131 # Asynchronous comprehensions
132 "async def f():\n [i async for b in c]",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200133 # Decorated FunctionDef
Miss Skeleton (bot)ba3a5662019-10-26 07:06:40 -0700134 "@deco1\n@deco2()\n@deco3(1)\ndef f(): pass",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200135 # Decorated AsyncFunctionDef
Miss Skeleton (bot)ba3a5662019-10-26 07:06:40 -0700136 "@deco1\n@deco2()\n@deco3(1)\nasync def f(): pass",
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200137 # Decorated ClassDef
Miss Skeleton (bot)ba3a5662019-10-26 07:06:40 -0700138 "@deco1\n@deco2()\n@deco3(1)\nclass C: pass",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200139 # Decorator with generator argument
140 "@deco(a for a in b)\ndef f(): pass",
Pablo Galindo0c9258a2019-03-18 13:51:53 +0000141 # Simple assignment expression
142 "(a := 1)",
Pablo Galindo2f58a842019-05-31 14:09:49 +0100143 # Positional-only arguments
144 "def f(a, /,): pass",
145 "def f(a, /, c, d, e): pass",
146 "def f(a, /, c, *, d, e): pass",
147 "def f(a, /, c, *, d, e, **kwargs): pass",
148 # Positional-only arguments with defaults
149 "def f(a=1, /,): pass",
150 "def f(a=1, /, b=2, c=4): pass",
151 "def f(a=1, /, b=2, *, c=4): pass",
152 "def f(a=1, /, b=2, *, c): pass",
153 "def f(a=1, /, b=2, *, c=4, **kwargs): pass",
154 "def f(a=1, /, b=2, *, c, **kwargs): pass",
Pablo Galindo0c9258a2019-03-18 13:51:53 +0000155
Tim Peters400cbc32006-02-28 18:44:41 +0000156]
157
158# These are compiled through "single"
159# because of overlap with "eval", it just tests what
160# can't be tested with "eval"
161single_tests = [
162 "1+2"
163]
164
165# These are compiled through "eval"
166# It should test all expressions
167eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500168 # None
169 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000170 # BoolOp
171 "a and b",
172 # BinOp
173 "a + b",
174 # UnaryOp
175 "not v",
176 # Lambda
177 "lambda:None",
178 # Dict
179 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500180 # Empty dict
181 "{}",
182 # Set
183 "{None,}",
184 # Multiline dict (test for .lineno & .col_offset)
185 """{
186 1
187 :
188 2
189 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000190 # ListComp
191 "[a for b in c if d]",
192 # GeneratorExp
193 "(a for b in c if d)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200194 # Comprehensions with multiple for targets
195 "[(a,b) for a,b in c]",
196 "[(a,b) for (a,b) in c]",
197 "[(a,b) for [a,b] in c]",
198 "{(a,b) for a,b in c}",
199 "{(a,b) for (a,b) in c}",
200 "{(a,b) for [a,b] in c}",
201 "((a,b) for a,b in c)",
202 "((a,b) for (a,b) in c)",
203 "((a,b) for [a,b] in c)",
Tim Peters400cbc32006-02-28 18:44:41 +0000204 # Yield - yield expressions can't work outside a function
205 #
206 # Compare
207 "1 < 2 < 3",
208 # Call
209 "f(1,2,c=3,*d,**e)",
Serhiy Storchakab619b092018-11-27 09:40:29 +0200210 # Call with a generator argument
211 "f(a for a in b)",
Tim Peters400cbc32006-02-28 18:44:41 +0000212 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000213 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000214 # Str
215 "'string'",
216 # Attribute
217 "a.b",
218 # Subscript
219 "a[b:c]",
220 # Name
221 "v",
222 # List
223 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500224 # Empty list
225 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000226 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000227 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500228 # Tuple
229 "(1,2,3)",
230 # Empty tuple
231 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000232 # Combination
233 "a.b.c.d(a.b[1:2])",
234
Tim Peters400cbc32006-02-28 18:44:41 +0000235]
236
237# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
238# excepthandler, arguments, keywords, alias
239
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000240class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000241
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500242 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000243 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000244 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000245 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000246 node_pos = (ast_node.lineno, ast_node.col_offset)
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200247 self.assertGreaterEqual(node_pos, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000248 parent_pos = (ast_node.lineno, ast_node.col_offset)
249 for name in ast_node._fields:
250 value = getattr(ast_node, name)
251 if isinstance(value, list):
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200252 first_pos = parent_pos
253 if value and name == 'decorator_list':
254 first_pos = (value[0].lineno, value[0].col_offset)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000255 for child in value:
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +0200256 self._assertTrueorder(child, first_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000257 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500258 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000259
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500260 def test_AST_objects(self):
261 x = ast.AST()
262 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700263 x.foobar = 42
264 self.assertEqual(x.foobar, 42)
265 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500266
267 with self.assertRaises(AttributeError):
268 x.vararg
269
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500270 with self.assertRaises(TypeError):
271 # "_ast.AST constructor takes 0 positional arguments"
272 ast.AST(2)
273
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700274 def test_AST_garbage_collection(self):
275 class X:
276 pass
277 a = ast.AST()
278 a.x = X()
279 a.x.a = a
280 ref = weakref.ref(a.x)
281 del a
282 support.gc_collect()
283 self.assertIsNone(ref())
284
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000285 def test_snippets(self):
286 for input, output, kind in ((exec_tests, exec_results, "exec"),
287 (single_tests, single_results, "single"),
288 (eval_tests, eval_results, "eval")):
289 for i, o in zip(input, output):
Yury Selivanovb3d53132015-09-01 16:10:49 -0400290 with self.subTest(action="parsing", input=i):
291 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
292 self.assertEqual(to_tuple(ast_tree), o)
293 self._assertTrueorder(ast_tree, (0, 0))
Victor Stinner15a30952016-02-08 22:45:06 +0100294 with self.subTest(action="compiling", input=i, kind=kind):
295 compile(ast_tree, "?", kind)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000296
Pablo Galindo0c9258a2019-03-18 13:51:53 +0000297 def test_ast_validation(self):
298 # compile() is the only function that calls PyAST_Validate
299 snippets_to_validate = exec_tests + single_tests + eval_tests
300 for snippet in snippets_to_validate:
301 tree = ast.parse(snippet)
302 compile(tree, '<string>', 'exec')
303
Benjamin Peterson78565b22009-06-28 19:19:51 +0000304 def test_slice(self):
305 slc = ast.parse("x[::]").body[0].value.slice
306 self.assertIsNone(slc.upper)
307 self.assertIsNone(slc.lower)
308 self.assertIsNone(slc.step)
309
310 def test_from_import(self):
311 im = ast.parse("from . import y").body[0]
312 self.assertIsNone(im.module)
313
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400314 def test_non_interned_future_from_ast(self):
315 mod = ast.parse("from __future__ import division")
316 self.assertIsInstance(mod.body[0], ast.ImportFrom)
317 mod.body[0].module = " __future__ ".strip()
318 compile(mod, "<test>", "exec")
319
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000320 def test_base_classes(self):
321 self.assertTrue(issubclass(ast.For, ast.stmt))
322 self.assertTrue(issubclass(ast.Name, ast.expr))
323 self.assertTrue(issubclass(ast.stmt, ast.AST))
324 self.assertTrue(issubclass(ast.expr, ast.AST))
325 self.assertTrue(issubclass(ast.comprehension, ast.AST))
326 self.assertTrue(issubclass(ast.Gt, ast.AST))
327
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500328 def test_field_attr_existence(self):
329 for name, item in ast.__dict__.items():
330 if isinstance(item, type) and name != 'AST' and name[0].isupper():
331 x = item()
332 if isinstance(x, ast.AST):
333 self.assertEqual(type(x._fields), tuple)
334
335 def test_arguments(self):
336 x = ast.arguments()
Miss Islington (bot)cf9a63c2019-07-14 16:49:52 -0700337 self.assertEqual(x._fields, ('posonlyargs', 'args', 'vararg', 'kwonlyargs',
338 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500339
340 with self.assertRaises(AttributeError):
341 x.vararg
342
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100343 x = ast.arguments(*range(1, 8))
344 self.assertEqual(x.vararg, 3)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500345
346 def test_field_attr_writable(self):
347 x = ast.Num()
348 # We can assign to _fields
349 x._fields = 666
350 self.assertEqual(x._fields, 666)
351
352 def test_classattrs(self):
353 x = ast.Num()
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700354 self.assertEqual(x._fields, ('value', 'kind'))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300355
356 with self.assertRaises(AttributeError):
357 x.value
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500358
359 with self.assertRaises(AttributeError):
360 x.n
361
362 x = ast.Num(42)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300363 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500364 self.assertEqual(x.n, 42)
365
366 with self.assertRaises(AttributeError):
367 x.lineno
368
369 with self.assertRaises(AttributeError):
370 x.foobar
371
372 x = ast.Num(lineno=2)
373 self.assertEqual(x.lineno, 2)
374
375 x = ast.Num(42, lineno=0)
376 self.assertEqual(x.lineno, 0)
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700377 self.assertEqual(x._fields, ('value', 'kind'))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300378 self.assertEqual(x.value, 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500379 self.assertEqual(x.n, 42)
380
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700381 self.assertRaises(TypeError, ast.Num, 1, None, 2)
382 self.assertRaises(TypeError, ast.Num, 1, None, 2, lineno=0)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500383
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300384 self.assertEqual(ast.Num(42).n, 42)
385 self.assertEqual(ast.Num(4.25).n, 4.25)
386 self.assertEqual(ast.Num(4.25j).n, 4.25j)
387 self.assertEqual(ast.Str('42').s, '42')
388 self.assertEqual(ast.Bytes(b'42').s, b'42')
389 self.assertIs(ast.NameConstant(True).value, True)
390 self.assertIs(ast.NameConstant(False).value, False)
391 self.assertIs(ast.NameConstant(None).value, None)
392
393 self.assertEqual(ast.Constant(42).value, 42)
394 self.assertEqual(ast.Constant(4.25).value, 4.25)
395 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
396 self.assertEqual(ast.Constant('42').value, '42')
397 self.assertEqual(ast.Constant(b'42').value, b'42')
398 self.assertIs(ast.Constant(True).value, True)
399 self.assertIs(ast.Constant(False).value, False)
400 self.assertIs(ast.Constant(None).value, None)
401 self.assertIs(ast.Constant(...).value, ...)
402
403 def test_realtype(self):
404 self.assertEqual(type(ast.Num(42)), ast.Constant)
405 self.assertEqual(type(ast.Num(4.25)), ast.Constant)
406 self.assertEqual(type(ast.Num(4.25j)), ast.Constant)
407 self.assertEqual(type(ast.Str('42')), ast.Constant)
408 self.assertEqual(type(ast.Bytes(b'42')), ast.Constant)
409 self.assertEqual(type(ast.NameConstant(True)), ast.Constant)
410 self.assertEqual(type(ast.NameConstant(False)), ast.Constant)
411 self.assertEqual(type(ast.NameConstant(None)), ast.Constant)
412 self.assertEqual(type(ast.Ellipsis()), ast.Constant)
413
414 def test_isinstance(self):
415 self.assertTrue(isinstance(ast.Num(42), ast.Num))
416 self.assertTrue(isinstance(ast.Num(4.2), ast.Num))
417 self.assertTrue(isinstance(ast.Num(4.2j), ast.Num))
418 self.assertTrue(isinstance(ast.Str('42'), ast.Str))
419 self.assertTrue(isinstance(ast.Bytes(b'42'), ast.Bytes))
420 self.assertTrue(isinstance(ast.NameConstant(True), ast.NameConstant))
421 self.assertTrue(isinstance(ast.NameConstant(False), ast.NameConstant))
422 self.assertTrue(isinstance(ast.NameConstant(None), ast.NameConstant))
423 self.assertTrue(isinstance(ast.Ellipsis(), ast.Ellipsis))
424
425 self.assertTrue(isinstance(ast.Constant(42), ast.Num))
426 self.assertTrue(isinstance(ast.Constant(4.2), ast.Num))
427 self.assertTrue(isinstance(ast.Constant(4.2j), ast.Num))
428 self.assertTrue(isinstance(ast.Constant('42'), ast.Str))
429 self.assertTrue(isinstance(ast.Constant(b'42'), ast.Bytes))
430 self.assertTrue(isinstance(ast.Constant(True), ast.NameConstant))
431 self.assertTrue(isinstance(ast.Constant(False), ast.NameConstant))
432 self.assertTrue(isinstance(ast.Constant(None), ast.NameConstant))
433 self.assertTrue(isinstance(ast.Constant(...), ast.Ellipsis))
434
435 self.assertFalse(isinstance(ast.Str('42'), ast.Num))
436 self.assertFalse(isinstance(ast.Num(42), ast.Str))
437 self.assertFalse(isinstance(ast.Str('42'), ast.Bytes))
438 self.assertFalse(isinstance(ast.Num(42), ast.NameConstant))
439 self.assertFalse(isinstance(ast.Num(42), ast.Ellipsis))
Anthony Sottile74176222019-01-18 11:30:28 -0800440 self.assertFalse(isinstance(ast.NameConstant(True), ast.Num))
441 self.assertFalse(isinstance(ast.NameConstant(False), ast.Num))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300442
443 self.assertFalse(isinstance(ast.Constant('42'), ast.Num))
444 self.assertFalse(isinstance(ast.Constant(42), ast.Str))
445 self.assertFalse(isinstance(ast.Constant('42'), ast.Bytes))
446 self.assertFalse(isinstance(ast.Constant(42), ast.NameConstant))
447 self.assertFalse(isinstance(ast.Constant(42), ast.Ellipsis))
Anthony Sottile74176222019-01-18 11:30:28 -0800448 self.assertFalse(isinstance(ast.Constant(True), ast.Num))
449 self.assertFalse(isinstance(ast.Constant(False), ast.Num))
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300450
451 self.assertFalse(isinstance(ast.Constant(), ast.Num))
452 self.assertFalse(isinstance(ast.Constant(), ast.Str))
453 self.assertFalse(isinstance(ast.Constant(), ast.Bytes))
454 self.assertFalse(isinstance(ast.Constant(), ast.NameConstant))
455 self.assertFalse(isinstance(ast.Constant(), ast.Ellipsis))
456
Serhiy Storchaka6015cc52018-10-28 13:43:03 +0200457 class S(str): pass
458 self.assertTrue(isinstance(ast.Constant(S('42')), ast.Str))
459 self.assertFalse(isinstance(ast.Constant(S('42')), ast.Num))
460
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300461 def test_subclasses(self):
462 class N(ast.Num):
463 def __init__(self, *args, **kwargs):
464 super().__init__(*args, **kwargs)
465 self.z = 'spam'
466 class N2(ast.Num):
467 pass
468
469 n = N(42)
470 self.assertEqual(n.n, 42)
471 self.assertEqual(n.z, 'spam')
472 self.assertEqual(type(n), N)
473 self.assertTrue(isinstance(n, N))
474 self.assertTrue(isinstance(n, ast.Num))
475 self.assertFalse(isinstance(n, N2))
476 self.assertFalse(isinstance(ast.Num(42), N))
477 n = N(n=42)
478 self.assertEqual(n.n, 42)
479 self.assertEqual(type(n), N)
480
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500481 def test_module(self):
482 body = [ast.Num(42)]
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800483 x = ast.Module(body, [])
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500484 self.assertEqual(x.body, body)
485
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000486 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100487 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500488 x = ast.BinOp()
489 self.assertEqual(x._fields, ('left', 'op', 'right'))
490
491 # Random attribute allowed too
492 x.foobarbaz = 5
493 self.assertEqual(x.foobarbaz, 5)
494
495 n1 = ast.Num(1)
496 n3 = ast.Num(3)
497 addop = ast.Add()
498 x = ast.BinOp(n1, addop, n3)
499 self.assertEqual(x.left, n1)
500 self.assertEqual(x.op, addop)
501 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500502
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500503 x = ast.BinOp(1, 2, 3)
504 self.assertEqual(x.left, 1)
505 self.assertEqual(x.op, 2)
506 self.assertEqual(x.right, 3)
507
Georg Brandl0c77a822008-06-10 16:37:50 +0000508 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000509 self.assertEqual(x.left, 1)
510 self.assertEqual(x.op, 2)
511 self.assertEqual(x.right, 3)
512 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000513
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500514 # node raises exception when given too many arguments
515 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500516 # node raises exception when given too many arguments
517 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000518
519 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000520 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000521 self.assertEqual(x.left, 1)
522 self.assertEqual(x.op, 2)
523 self.assertEqual(x.right, 3)
524 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000525
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500526 # Random kwargs also allowed
527 x = ast.BinOp(1, 2, 3, foobarbaz=42)
528 self.assertEqual(x.foobarbaz, 42)
529
530 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000531 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000532 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500533 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000534
535 def test_pickling(self):
536 import pickle
537 mods = [pickle]
538 try:
539 import cPickle
540 mods.append(cPickle)
541 except ImportError:
542 pass
543 protocols = [0, 1, 2]
544 for mod in mods:
545 for protocol in protocols:
546 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
547 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000548 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000549
Benjamin Peterson5b066812010-11-20 01:38:49 +0000550 def test_invalid_sum(self):
551 pos = dict(lineno=2, col_offset=3)
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800552 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], [])
Benjamin Peterson5b066812010-11-20 01:38:49 +0000553 with self.assertRaises(TypeError) as cm:
554 compile(m, "<test>", "exec")
555 self.assertIn("but got <_ast.expr", str(cm.exception))
556
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500557 def test_invalid_identitifer(self):
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800558 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))], [])
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500559 ast.fix_missing_locations(m)
560 with self.assertRaises(TypeError) as cm:
561 compile(m, "<test>", "exec")
562 self.assertIn("identifier must be of type str", str(cm.exception))
563
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000564 def test_empty_yield_from(self):
565 # Issue 16546: yield from value is not optional.
566 empty_yield_from = ast.parse("def f():\n yield from g()")
567 empty_yield_from.body[0].body[0].value.value = None
568 with self.assertRaises(ValueError) as cm:
569 compile(empty_yield_from, "<test>", "exec")
570 self.assertIn("field value is required", str(cm.exception))
571
Oren Milman7dc46d82017-09-30 20:16:24 +0300572 @support.cpython_only
573 def test_issue31592(self):
574 # There shouldn't be an assertion failure in case of a bad
575 # unicodedata.normalize().
576 import unicodedata
577 def bad_normalize(*args):
578 return None
579 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
580 self.assertRaises(TypeError, ast.parse, '\u03D5')
581
Miss Islington (bot)c7be35c2019-07-08 14:41:34 -0700582 def test_issue18374_binop_col_offset(self):
583 tree = ast.parse('4+5+6+7')
584 parent_binop = tree.body[0].value
585 child_binop = parent_binop.left
586 grandchild_binop = child_binop.left
587 self.assertEqual(parent_binop.col_offset, 0)
588 self.assertEqual(parent_binop.end_col_offset, 7)
589 self.assertEqual(child_binop.col_offset, 0)
590 self.assertEqual(child_binop.end_col_offset, 5)
591 self.assertEqual(grandchild_binop.col_offset, 0)
592 self.assertEqual(grandchild_binop.end_col_offset, 3)
593
594 tree = ast.parse('4+5-\\\n 6-7')
595 parent_binop = tree.body[0].value
596 child_binop = parent_binop.left
597 grandchild_binop = child_binop.left
598 self.assertEqual(parent_binop.col_offset, 0)
599 self.assertEqual(parent_binop.lineno, 1)
600 self.assertEqual(parent_binop.end_col_offset, 4)
601 self.assertEqual(parent_binop.end_lineno, 2)
602
603 self.assertEqual(child_binop.col_offset, 0)
Miss Islington (bot)68bd9c52019-07-09 06:28:57 -0700604 self.assertEqual(child_binop.lineno, 1)
Miss Islington (bot)c7be35c2019-07-08 14:41:34 -0700605 self.assertEqual(child_binop.end_col_offset, 2)
Miss Islington (bot)68bd9c52019-07-09 06:28:57 -0700606 self.assertEqual(child_binop.end_lineno, 2)
Miss Islington (bot)c7be35c2019-07-08 14:41:34 -0700607
608 self.assertEqual(grandchild_binop.col_offset, 0)
Miss Islington (bot)68bd9c52019-07-09 06:28:57 -0700609 self.assertEqual(grandchild_binop.lineno, 1)
Miss Islington (bot)c7be35c2019-07-08 14:41:34 -0700610 self.assertEqual(grandchild_binop.end_col_offset, 3)
Miss Islington (bot)68bd9c52019-07-09 06:28:57 -0700611 self.assertEqual(grandchild_binop.end_lineno, 1)
Georg Brandl0c77a822008-06-10 16:37:50 +0000612
613class ASTHelpers_Test(unittest.TestCase):
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700614 maxDiff = None
Georg Brandl0c77a822008-06-10 16:37:50 +0000615
616 def test_parse(self):
617 a = ast.parse('foo(1 + 1)')
618 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
619 self.assertEqual(ast.dump(a), ast.dump(b))
620
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400621 def test_parse_in_error(self):
622 try:
623 1/0
624 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400625 with self.assertRaises(SyntaxError) as e:
626 ast.literal_eval(r"'\U'")
627 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400628
Georg Brandl0c77a822008-06-10 16:37:50 +0000629 def test_dump(self):
630 node = ast.parse('spam(eggs, "and cheese")')
631 self.assertEqual(ast.dump(node),
632 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700633 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese', kind=None)], "
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800634 "keywords=[]))], type_ignores=[])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000635 )
636 self.assertEqual(ast.dump(node, annotate_fields=False),
637 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700638 "Constant('and cheese', None)], []))], [])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000639 )
640 self.assertEqual(ast.dump(node, include_attributes=True),
641 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000642 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), "
643 "args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700644 "end_lineno=1, end_col_offset=9), Constant(value='and cheese', kind=None, "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000645 "lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], keywords=[], "
646 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), "
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800647 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24)], type_ignores=[])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000648 )
649
Serhiy Storchaka097eae52019-08-29 10:50:28 +0300650 def test_dump_incomplete(self):
651 node = ast.Raise(lineno=3, col_offset=4)
652 self.assertEqual(ast.dump(node),
653 "Raise()"
654 )
655 self.assertEqual(ast.dump(node, include_attributes=True),
656 "Raise(lineno=3, col_offset=4)"
657 )
658 node = ast.Raise(exc=ast.Name(id='e', ctx=ast.Load()), lineno=3, col_offset=4)
659 self.assertEqual(ast.dump(node),
660 "Raise(exc=Name(id='e', ctx=Load()))"
661 )
662 self.assertEqual(ast.dump(node, annotate_fields=False),
663 "Raise(Name('e', Load()))"
664 )
665 self.assertEqual(ast.dump(node, include_attributes=True),
666 "Raise(exc=Name(id='e', ctx=Load()), lineno=3, col_offset=4)"
667 )
668 self.assertEqual(ast.dump(node, annotate_fields=False, include_attributes=True),
669 "Raise(Name('e', Load()), lineno=3, col_offset=4)"
670 )
671 node = ast.Raise(cause=ast.Name(id='e', ctx=ast.Load()))
672 self.assertEqual(ast.dump(node),
673 "Raise(cause=Name(id='e', ctx=Load()))"
674 )
675 self.assertEqual(ast.dump(node, annotate_fields=False),
676 "Raise(cause=Name('e', Load()))"
677 )
678
Georg Brandl0c77a822008-06-10 16:37:50 +0000679 def test_copy_location(self):
680 src = ast.parse('1 + 1', mode='eval')
681 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
682 self.assertEqual(ast.dump(src, include_attributes=True),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700683 'Expression(body=BinOp(left=Constant(value=1, kind=None, lineno=1, col_offset=0, '
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000684 'end_lineno=1, end_col_offset=1), op=Add(), right=Constant(value=2, '
685 'lineno=1, col_offset=4, end_lineno=1, end_col_offset=5), lineno=1, '
686 'col_offset=0, end_lineno=1, end_col_offset=5))'
Georg Brandl0c77a822008-06-10 16:37:50 +0000687 )
688
689 def test_fix_missing_locations(self):
690 src = ast.parse('write("spam")')
691 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400692 [ast.Str('eggs')], [])))
Georg Brandl0c77a822008-06-10 16:37:50 +0000693 self.assertEqual(src, ast.fix_missing_locations(src))
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000694 self.maxDiff = None
Georg Brandl0c77a822008-06-10 16:37:50 +0000695 self.assertEqual(ast.dump(src, include_attributes=True),
696 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000697 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), "
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700698 "args=[Constant(value='spam', kind=None, lineno=1, col_offset=6, end_lineno=1, "
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000699 "end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
700 "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, "
701 "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), "
702 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), "
703 "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, "
704 "end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800705 "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)], "
706 "type_ignores=[])"
Georg Brandl0c77a822008-06-10 16:37:50 +0000707 )
708
709 def test_increment_lineno(self):
710 src = ast.parse('1 + 1', mode='eval')
711 self.assertEqual(ast.increment_lineno(src, n=3), src)
712 self.assertEqual(ast.dump(src, include_attributes=True),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700713 'Expression(body=BinOp(left=Constant(value=1, kind=None, lineno=4, col_offset=0, '
714 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, kind=None, '
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000715 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
716 'col_offset=0, end_lineno=4, end_col_offset=5))'
Georg Brandl0c77a822008-06-10 16:37:50 +0000717 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000718 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000719 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000720 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
721 self.assertEqual(ast.dump(src, include_attributes=True),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700722 'Expression(body=BinOp(left=Constant(value=1, kind=None, lineno=4, col_offset=0, '
723 'end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, kind=None, '
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000724 'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
725 'col_offset=0, end_lineno=4, end_col_offset=5))'
Georg Brandl619e7ba2011-01-09 07:38:51 +0000726 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000727
728 def test_iter_fields(self):
729 node = ast.parse('foo()', mode='eval')
730 d = dict(ast.iter_fields(node.body))
731 self.assertEqual(d.pop('func').id, 'foo')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400732 self.assertEqual(d, {'keywords': [], 'args': []})
Georg Brandl0c77a822008-06-10 16:37:50 +0000733
734 def test_iter_child_nodes(self):
735 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
736 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
737 iterator = ast.iter_child_nodes(node.body)
738 self.assertEqual(next(iterator).id, 'spam')
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300739 self.assertEqual(next(iterator).value, 23)
740 self.assertEqual(next(iterator).value, 42)
Georg Brandl0c77a822008-06-10 16:37:50 +0000741 self.assertEqual(ast.dump(next(iterator)),
Guido van Rossum10f8ce62019-03-13 13:00:46 -0700742 "keyword(arg='eggs', value=Constant(value='leek', kind=None))"
Georg Brandl0c77a822008-06-10 16:37:50 +0000743 )
744
745 def test_get_docstring(self):
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300746 node = ast.parse('"""line one\n line two"""')
747 self.assertEqual(ast.get_docstring(node),
748 'line one\nline two')
749
750 node = ast.parse('class foo:\n """line one\n line two"""')
751 self.assertEqual(ast.get_docstring(node.body[0]),
752 'line one\nline two')
753
Georg Brandl0c77a822008-06-10 16:37:50 +0000754 node = ast.parse('def foo():\n """line one\n line two"""')
755 self.assertEqual(ast.get_docstring(node.body[0]),
756 'line one\nline two')
757
Yury Selivanov2f07a662015-07-23 08:54:35 +0300758 node = ast.parse('async def foo():\n """spam\n ham"""')
759 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300760
761 def test_get_docstring_none(self):
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800762 self.assertIsNone(ast.get_docstring(ast.parse('')))
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300763 node = ast.parse('x = "not docstring"')
764 self.assertIsNone(ast.get_docstring(node))
765 node = ast.parse('def foo():\n pass')
766 self.assertIsNone(ast.get_docstring(node))
767
768 node = ast.parse('class foo:\n pass')
769 self.assertIsNone(ast.get_docstring(node.body[0]))
770 node = ast.parse('class foo:\n x = "not docstring"')
771 self.assertIsNone(ast.get_docstring(node.body[0]))
772 node = ast.parse('class foo:\n def bar(self): pass')
773 self.assertIsNone(ast.get_docstring(node.body[0]))
774
775 node = ast.parse('def foo():\n pass')
776 self.assertIsNone(ast.get_docstring(node.body[0]))
777 node = ast.parse('def foo():\n x = "not docstring"')
778 self.assertIsNone(ast.get_docstring(node.body[0]))
779
780 node = ast.parse('async def foo():\n pass')
781 self.assertIsNone(ast.get_docstring(node.body[0]))
782 node = ast.parse('async def foo():\n x = "not docstring"')
783 self.assertIsNone(ast.get_docstring(node.body[0]))
Yury Selivanov2f07a662015-07-23 08:54:35 +0300784
Anthony Sottile995d9b92019-01-12 20:05:13 -0800785 def test_multi_line_docstring_col_offset_and_lineno_issue16806(self):
786 node = ast.parse(
787 '"""line one\nline two"""\n\n'
788 'def foo():\n """line one\n line two"""\n\n'
789 ' def bar():\n """line one\n line two"""\n'
790 ' """line one\n line two"""\n'
791 '"""line one\nline two"""\n\n'
792 )
793 self.assertEqual(node.body[0].col_offset, 0)
794 self.assertEqual(node.body[0].lineno, 1)
795 self.assertEqual(node.body[1].body[0].col_offset, 2)
796 self.assertEqual(node.body[1].body[0].lineno, 5)
797 self.assertEqual(node.body[1].body[1].body[0].col_offset, 4)
798 self.assertEqual(node.body[1].body[1].body[0].lineno, 9)
799 self.assertEqual(node.body[1].body[2].col_offset, 2)
800 self.assertEqual(node.body[1].body[2].lineno, 11)
801 self.assertEqual(node.body[2].col_offset, 0)
802 self.assertEqual(node.body[2].lineno, 13)
803
Miss Islington (bot)3b18b172019-12-13 08:21:54 -0800804 def test_elif_stmt_start_position(self):
805 node = ast.parse('if a:\n pass\nelif b:\n pass\n')
806 elif_stmt = node.body[0].orelse[0]
807 self.assertEqual(elif_stmt.lineno, 3)
808 self.assertEqual(elif_stmt.col_offset, 0)
809
Georg Brandl0c77a822008-06-10 16:37:50 +0000810 def test_literal_eval(self):
811 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
812 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
813 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000814 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000815 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000816 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200817 self.assertEqual(ast.literal_eval('6'), 6)
818 self.assertEqual(ast.literal_eval('+6'), 6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000819 self.assertEqual(ast.literal_eval('-6'), -6)
Raymond Hettingerbc959732010-10-08 00:47:45 +0000820 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200821 self.assertEqual(ast.literal_eval('+3.25'), 3.25)
822 self.assertEqual(ast.literal_eval('-3.25'), -3.25)
823 self.assertEqual(repr(ast.literal_eval('-0.0')), '-0.0')
824 self.assertRaises(ValueError, ast.literal_eval, '++6')
825 self.assertRaises(ValueError, ast.literal_eval, '+True')
826 self.assertRaises(ValueError, ast.literal_eval, '2+3')
Georg Brandl0c77a822008-06-10 16:37:50 +0000827
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200828 def test_literal_eval_complex(self):
829 # Issue #4907
830 self.assertEqual(ast.literal_eval('6j'), 6j)
831 self.assertEqual(ast.literal_eval('-6j'), -6j)
832 self.assertEqual(ast.literal_eval('6.75j'), 6.75j)
833 self.assertEqual(ast.literal_eval('-6.75j'), -6.75j)
834 self.assertEqual(ast.literal_eval('3+6j'), 3+6j)
835 self.assertEqual(ast.literal_eval('-3+6j'), -3+6j)
836 self.assertEqual(ast.literal_eval('3-6j'), 3-6j)
837 self.assertEqual(ast.literal_eval('-3-6j'), -3-6j)
838 self.assertEqual(ast.literal_eval('3.25+6.75j'), 3.25+6.75j)
839 self.assertEqual(ast.literal_eval('-3.25+6.75j'), -3.25+6.75j)
840 self.assertEqual(ast.literal_eval('3.25-6.75j'), 3.25-6.75j)
841 self.assertEqual(ast.literal_eval('-3.25-6.75j'), -3.25-6.75j)
842 self.assertEqual(ast.literal_eval('(3+6j)'), 3+6j)
843 self.assertRaises(ValueError, ast.literal_eval, '-6j+3')
844 self.assertRaises(ValueError, ast.literal_eval, '-6j+3j')
845 self.assertRaises(ValueError, ast.literal_eval, '3+-6j')
846 self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
847 self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000848
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100849 def test_bad_integer(self):
850 # issue13436: Bad error message with invalid numeric values
851 body = [ast.ImportFrom(module='time',
852 names=[ast.alias(name='sleep')],
853 level=None,
854 lineno=None, col_offset=None)]
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800855 mod = ast.Module(body, [])
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100856 with self.assertRaises(ValueError) as cm:
857 compile(mod, 'test', 'exec')
858 self.assertIn("invalid integer value: None", str(cm.exception))
859
Berker Peksag0a5bd512016-04-29 19:50:02 +0300860 def test_level_as_none(self):
861 body = [ast.ImportFrom(module='time',
862 names=[ast.alias(name='sleep')],
863 level=None,
864 lineno=0, col_offset=0)]
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800865 mod = ast.Module(body, [])
Berker Peksag0a5bd512016-04-29 19:50:02 +0300866 code = compile(mod, 'test', 'exec')
867 ns = {}
868 exec(code, ns)
869 self.assertIn('sleep', ns)
870
Georg Brandl0c77a822008-06-10 16:37:50 +0000871
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500872class ASTValidatorTests(unittest.TestCase):
873
874 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
875 mod.lineno = mod.col_offset = 0
876 ast.fix_missing_locations(mod)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300877 if msg is None:
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500878 compile(mod, "<test>", mode)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300879 else:
880 with self.assertRaises(exc) as cm:
881 compile(mod, "<test>", mode)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500882 self.assertIn(msg, str(cm.exception))
883
884 def expr(self, node, msg=None, *, exc=ValueError):
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800885 mod = ast.Module([ast.Expr(node)], [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500886 self.mod(mod, msg, exc=exc)
887
888 def stmt(self, stmt, msg=None):
Guido van Rossumdcfcd142019-01-31 03:40:27 -0800889 mod = ast.Module([stmt], [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500890 self.mod(mod, msg)
891
892 def test_module(self):
893 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
894 self.mod(m, "must have Load context", "single")
895 m = ast.Expression(ast.Name("x", ast.Store()))
896 self.mod(m, "must have Load context", "eval")
897
898 def _check_arguments(self, fac, check):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100899 def arguments(args=None, posonlyargs=None, vararg=None,
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700900 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500901 defaults=None, kw_defaults=None):
902 if args is None:
903 args = []
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100904 if posonlyargs is None:
905 posonlyargs = []
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500906 if kwonlyargs is None:
907 kwonlyargs = []
908 if defaults is None:
909 defaults = []
910 if kw_defaults is None:
911 kw_defaults = []
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100912 args = ast.arguments(args, posonlyargs, vararg, kwonlyargs,
913 kw_defaults, kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500914 return fac(args)
915 args = [ast.arg("x", ast.Name("x", ast.Store()))]
916 check(arguments(args=args), "must have Load context")
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100917 check(arguments(posonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500918 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500919 check(arguments(defaults=[ast.Num(3)]),
920 "more positional defaults than args")
921 check(arguments(kw_defaults=[ast.Num(4)]),
922 "length of kwonlyargs is not the same as kw_defaults")
923 args = [ast.arg("x", ast.Name("x", ast.Load()))]
924 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
925 "must have Load context")
926 args = [ast.arg("a", ast.Name("x", ast.Load())),
927 ast.arg("b", ast.Name("y", ast.Load()))]
928 check(arguments(kwonlyargs=args,
929 kw_defaults=[None, ast.Name("x", ast.Store())]),
930 "must have Load context")
931
932 def test_funcdef(self):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100933 a = ast.arguments([], [], None, [], [], None, [])
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300934 f = ast.FunctionDef("x", a, [], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500935 self.stmt(f, "empty body on FunctionDef")
936 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300937 None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500938 self.stmt(f, "must have Load context")
939 f = ast.FunctionDef("x", a, [ast.Pass()], [],
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300940 ast.Name("x", ast.Store()))
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500941 self.stmt(f, "must have Load context")
942 def fac(args):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300943 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500944 self._check_arguments(fac, self.stmt)
945
946 def test_classdef(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400947 def cls(bases=None, keywords=None, body=None, decorator_list=None):
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500948 if bases is None:
949 bases = []
950 if keywords is None:
951 keywords = []
952 if body is None:
953 body = [ast.Pass()]
954 if decorator_list is None:
955 decorator_list = []
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400956 return ast.ClassDef("myclass", bases, keywords,
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300957 body, decorator_list)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500958 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
959 "must have Load context")
960 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
961 "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500962 self.stmt(cls(body=[]), "empty body on ClassDef")
963 self.stmt(cls(body=[None]), "None disallowed")
964 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
965 "must have Load context")
966
967 def test_delete(self):
968 self.stmt(ast.Delete([]), "empty targets on Delete")
969 self.stmt(ast.Delete([None]), "None disallowed")
970 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
971 "must have Del context")
972
973 def test_assign(self):
974 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
975 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
976 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
977 "must have Store context")
978 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
979 ast.Name("y", ast.Store())),
980 "must have Load context")
981
982 def test_augassign(self):
983 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
984 ast.Name("y", ast.Load()))
985 self.stmt(aug, "must have Store context")
986 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
987 ast.Name("y", ast.Store()))
988 self.stmt(aug, "must have Load context")
989
990 def test_for(self):
991 x = ast.Name("x", ast.Store())
992 y = ast.Name("y", ast.Load())
993 p = ast.Pass()
994 self.stmt(ast.For(x, y, [], []), "empty body on For")
995 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
996 "must have Store context")
997 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
998 "must have Load context")
999 e = ast.Expr(ast.Name("x", ast.Store()))
1000 self.stmt(ast.For(x, y, [e], []), "must have Load context")
1001 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
1002
1003 def test_while(self):
1004 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
1005 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
1006 "must have Load context")
1007 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
1008 [ast.Expr(ast.Name("x", ast.Store()))]),
1009 "must have Load context")
1010
1011 def test_if(self):
1012 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
1013 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
1014 self.stmt(i, "must have Load context")
1015 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
1016 self.stmt(i, "must have Load context")
1017 i = ast.If(ast.Num(3), [ast.Pass()],
1018 [ast.Expr(ast.Name("x", ast.Store()))])
1019 self.stmt(i, "must have Load context")
1020
1021 def test_with(self):
1022 p = ast.Pass()
1023 self.stmt(ast.With([], [p]), "empty items on With")
1024 i = ast.withitem(ast.Num(3), None)
1025 self.stmt(ast.With([i], []), "empty body on With")
1026 i = ast.withitem(ast.Name("x", ast.Store()), None)
1027 self.stmt(ast.With([i], [p]), "must have Load context")
1028 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
1029 self.stmt(ast.With([i], [p]), "must have Store context")
1030
1031 def test_raise(self):
1032 r = ast.Raise(None, ast.Num(3))
1033 self.stmt(r, "Raise with cause but no exception")
1034 r = ast.Raise(ast.Name("x", ast.Store()), None)
1035 self.stmt(r, "must have Load context")
1036 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
1037 self.stmt(r, "must have Load context")
1038
1039 def test_try(self):
1040 p = ast.Pass()
1041 t = ast.Try([], [], [], [p])
1042 self.stmt(t, "empty body on Try")
1043 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
1044 self.stmt(t, "must have Load context")
1045 t = ast.Try([p], [], [], [])
1046 self.stmt(t, "Try has neither except handlers nor finalbody")
1047 t = ast.Try([p], [], [p], [p])
1048 self.stmt(t, "Try has orelse but no except handlers")
1049 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
1050 self.stmt(t, "empty body on ExceptHandler")
1051 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
1052 self.stmt(ast.Try([p], e, [], []), "must have Load context")
1053 e = [ast.ExceptHandler(None, "x", [p])]
1054 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
1055 self.stmt(t, "must have Load context")
1056 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
1057 self.stmt(t, "must have Load context")
1058
1059 def test_assert(self):
1060 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
1061 "must have Load context")
1062 assrt = ast.Assert(ast.Name("x", ast.Load()),
1063 ast.Name("y", ast.Store()))
1064 self.stmt(assrt, "must have Load context")
1065
1066 def test_import(self):
1067 self.stmt(ast.Import([]), "empty names on Import")
1068
1069 def test_importfrom(self):
1070 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
Serhiy Storchaka7de28402016-06-27 23:40:43 +03001071 self.stmt(imp, "Negative ImportFrom level")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001072 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
1073
1074 def test_global(self):
1075 self.stmt(ast.Global([]), "empty names on Global")
1076
1077 def test_nonlocal(self):
1078 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
1079
1080 def test_expr(self):
1081 e = ast.Expr(ast.Name("x", ast.Store()))
1082 self.stmt(e, "must have Load context")
1083
1084 def test_boolop(self):
1085 b = ast.BoolOp(ast.And(), [])
1086 self.expr(b, "less than 2 values")
1087 b = ast.BoolOp(ast.And(), [ast.Num(3)])
1088 self.expr(b, "less than 2 values")
1089 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
1090 self.expr(b, "None disallowed")
1091 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
1092 self.expr(b, "must have Load context")
1093
1094 def test_unaryop(self):
1095 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
1096 self.expr(u, "must have Load context")
1097
1098 def test_lambda(self):
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001099 a = ast.arguments([], [], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001100 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
1101 "must have Load context")
1102 def fac(args):
1103 return ast.Lambda(args, ast.Name("x", ast.Load()))
1104 self._check_arguments(fac, self.expr)
1105
1106 def test_ifexp(self):
1107 l = ast.Name("x", ast.Load())
1108 s = ast.Name("y", ast.Store())
1109 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -05001110 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001111
1112 def test_dict(self):
1113 d = ast.Dict([], [ast.Name("x", ast.Load())])
1114 self.expr(d, "same number of keys as values")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001115 d = ast.Dict([ast.Name("x", ast.Load())], [None])
1116 self.expr(d, "None disallowed")
1117
1118 def test_set(self):
1119 self.expr(ast.Set([None]), "None disallowed")
1120 s = ast.Set([ast.Name("x", ast.Store())])
1121 self.expr(s, "must have Load context")
1122
1123 def _check_comprehension(self, fac):
1124 self.expr(fac([]), "comprehension with no generators")
1125 g = ast.comprehension(ast.Name("x", ast.Load()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001126 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001127 self.expr(fac([g]), "must have Store context")
1128 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001129 ast.Name("x", ast.Store()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001130 self.expr(fac([g]), "must have Load context")
1131 x = ast.Name("x", ast.Store())
1132 y = ast.Name("y", ast.Load())
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001133 g = ast.comprehension(x, y, [None], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001134 self.expr(fac([g]), "None disallowed")
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001135 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001136 self.expr(fac([g]), "must have Load context")
1137
1138 def _simple_comp(self, fac):
1139 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001140 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001141 self.expr(fac(ast.Name("x", ast.Store()), [g]),
1142 "must have Load context")
1143 def wrap(gens):
1144 return fac(ast.Name("x", ast.Store()), gens)
1145 self._check_comprehension(wrap)
1146
1147 def test_listcomp(self):
1148 self._simple_comp(ast.ListComp)
1149
1150 def test_setcomp(self):
1151 self._simple_comp(ast.SetComp)
1152
1153 def test_generatorexp(self):
1154 self._simple_comp(ast.GeneratorExp)
1155
1156 def test_dictcomp(self):
1157 g = ast.comprehension(ast.Name("y", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001158 ast.Name("p", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001159 c = ast.DictComp(ast.Name("x", ast.Store()),
1160 ast.Name("y", ast.Load()), [g])
1161 self.expr(c, "must have Load context")
1162 c = ast.DictComp(ast.Name("x", ast.Load()),
1163 ast.Name("y", ast.Store()), [g])
1164 self.expr(c, "must have Load context")
1165 def factory(comps):
1166 k = ast.Name("x", ast.Load())
1167 v = ast.Name("y", ast.Load())
1168 return ast.DictComp(k, v, comps)
1169 self._check_comprehension(factory)
1170
1171 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -05001172 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
1173 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001174
1175 def test_compare(self):
1176 left = ast.Name("x", ast.Load())
1177 comp = ast.Compare(left, [ast.In()], [])
1178 self.expr(comp, "no comparators")
1179 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
1180 self.expr(comp, "different number of comparators and operands")
1181 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001182 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001183 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001184 self.expr(comp)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001185
1186 def test_call(self):
1187 func = ast.Name("x", ast.Load())
1188 args = [ast.Name("y", ast.Load())]
1189 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001190 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001191 self.expr(call, "must have Load context")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001192 call = ast.Call(func, [None], keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001193 self.expr(call, "None disallowed")
1194 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001195 call = ast.Call(func, args, bad_keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001196 self.expr(call, "must have Load context")
1197
1198 def test_num(self):
1199 class subint(int):
1200 pass
1201 class subfloat(float):
1202 pass
1203 class subcomplex(complex):
1204 pass
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001205 for obj in "0", "hello":
1206 self.expr(ast.Num(obj))
1207 for obj in subint(), subfloat(), subcomplex():
1208 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001209
1210 def test_attribute(self):
1211 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
1212 self.expr(attr, "must have Load context")
1213
1214 def test_subscript(self):
1215 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
1216 ast.Load())
1217 self.expr(sub, "must have Load context")
1218 x = ast.Name("x", ast.Load())
1219 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
1220 ast.Load())
1221 self.expr(sub, "must have Load context")
1222 s = ast.Name("x", ast.Store())
1223 for args in (s, None, None), (None, s, None), (None, None, s):
1224 sl = ast.Slice(*args)
1225 self.expr(ast.Subscript(x, sl, ast.Load()),
1226 "must have Load context")
1227 sl = ast.ExtSlice([])
1228 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
1229 sl = ast.ExtSlice([ast.Index(s)])
1230 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
1231
1232 def test_starred(self):
1233 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
1234 ast.Store())
1235 assign = ast.Assign([left], ast.Num(4))
1236 self.stmt(assign, "must have Store context")
1237
1238 def _sequence(self, fac):
1239 self.expr(fac([None], ast.Load()), "None disallowed")
1240 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
1241 "must have Load context")
1242
1243 def test_list(self):
1244 self._sequence(ast.List)
1245
1246 def test_tuple(self):
1247 self._sequence(ast.Tuple)
1248
Benjamin Peterson442f2092012-12-06 17:41:04 -05001249 def test_nameconstant(self):
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001250 self.expr(ast.NameConstant(4))
Benjamin Peterson442f2092012-12-06 17:41:04 -05001251
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001252 def test_stdlib_validates(self):
1253 stdlib = os.path.dirname(ast.__file__)
1254 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
1255 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
1256 for module in tests:
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001257 with self.subTest(module):
1258 fn = os.path.join(stdlib, module)
1259 with open(fn, "r", encoding="utf-8") as fp:
1260 source = fp.read()
1261 mod = ast.parse(source, fn)
1262 compile(mod, fn, "exec")
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001263
1264
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001265class ConstantTests(unittest.TestCase):
1266 """Tests on the ast.Constant node type."""
1267
1268 def compile_constant(self, value):
1269 tree = ast.parse("x = 123")
1270
1271 node = tree.body[0].value
1272 new_node = ast.Constant(value=value)
1273 ast.copy_location(new_node, node)
1274 tree.body[0].value = new_node
1275
1276 code = compile(tree, "<string>", "exec")
1277
1278 ns = {}
1279 exec(code, ns)
1280 return ns['x']
1281
Victor Stinnerbe59d142016-01-27 00:39:12 +01001282 def test_validation(self):
1283 with self.assertRaises(TypeError) as cm:
1284 self.compile_constant([1, 2, 3])
1285 self.assertEqual(str(cm.exception),
1286 "got an invalid type in Constant: list")
1287
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001288 def test_singletons(self):
1289 for const in (None, False, True, Ellipsis, b'', frozenset()):
1290 with self.subTest(const=const):
1291 value = self.compile_constant(const)
1292 self.assertIs(value, const)
1293
1294 def test_values(self):
1295 nested_tuple = (1,)
1296 nested_frozenset = frozenset({1})
1297 for level in range(3):
1298 nested_tuple = (nested_tuple, 2)
1299 nested_frozenset = frozenset({nested_frozenset, 2})
1300 values = (123, 123.0, 123j,
1301 "unicode", b'bytes',
1302 tuple("tuple"), frozenset("frozenset"),
1303 nested_tuple, nested_frozenset)
1304 for value in values:
1305 with self.subTest(value=value):
1306 result = self.compile_constant(value)
1307 self.assertEqual(result, value)
1308
1309 def test_assign_to_constant(self):
1310 tree = ast.parse("x = 1")
1311
1312 target = tree.body[0].targets[0]
1313 new_target = ast.Constant(value=1)
1314 ast.copy_location(new_target, target)
1315 tree.body[0].targets[0] = new_target
1316
1317 with self.assertRaises(ValueError) as cm:
1318 compile(tree, "string", "exec")
1319 self.assertEqual(str(cm.exception),
1320 "expression which can't be assigned "
1321 "to in Store context")
1322
1323 def test_get_docstring(self):
1324 tree = ast.parse("'docstring'\nx = 1")
1325 self.assertEqual(ast.get_docstring(tree), 'docstring')
1326
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001327 def get_load_const(self, tree):
1328 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1329 # instructions
1330 co = compile(tree, '<string>', 'exec')
1331 consts = []
1332 for instr in dis.get_instructions(co):
1333 if instr.opname == 'LOAD_CONST':
1334 consts.append(instr.argval)
1335 return consts
1336
1337 @support.cpython_only
1338 def test_load_const(self):
1339 consts = [None,
1340 True, False,
1341 124,
1342 2.0,
1343 3j,
1344 "unicode",
1345 b'bytes',
1346 (1, 2, 3)]
1347
Victor Stinnera2724092016-02-08 18:17:58 +01001348 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1349 code += '\nx = ...'
1350 consts.extend((Ellipsis, None))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001351
1352 tree = ast.parse(code)
Victor Stinnera2724092016-02-08 18:17:58 +01001353 self.assertEqual(self.get_load_const(tree),
1354 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001355
1356 # Replace expression nodes with constants
Victor Stinnera2724092016-02-08 18:17:58 +01001357 for assign, const in zip(tree.body, consts):
1358 assert isinstance(assign, ast.Assign), ast.dump(assign)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001359 new_node = ast.Constant(value=const)
Victor Stinnera2724092016-02-08 18:17:58 +01001360 ast.copy_location(new_node, assign.value)
1361 assign.value = new_node
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001362
Victor Stinnera2724092016-02-08 18:17:58 +01001363 self.assertEqual(self.get_load_const(tree),
1364 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001365
1366 def test_literal_eval(self):
1367 tree = ast.parse("1 + 2")
1368 binop = tree.body[0].value
1369
1370 new_left = ast.Constant(value=10)
1371 ast.copy_location(new_left, binop.left)
1372 binop.left = new_left
1373
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001374 new_right = ast.Constant(value=20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001375 ast.copy_location(new_right, binop.right)
1376 binop.right = new_right
1377
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +02001378 self.assertEqual(ast.literal_eval(binop), 10+20j)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001379
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001380 def test_string_kind(self):
1381 c = ast.parse('"x"', mode='eval').body
1382 self.assertEqual(c.value, "x")
1383 self.assertEqual(c.kind, None)
1384
1385 c = ast.parse('u"x"', mode='eval').body
1386 self.assertEqual(c.value, "x")
1387 self.assertEqual(c.kind, "u")
1388
1389 c = ast.parse('r"x"', mode='eval').body
1390 self.assertEqual(c.value, "x")
1391 self.assertEqual(c.kind, None)
1392
1393 c = ast.parse('b"x"', mode='eval').body
1394 self.assertEqual(c.value, b"x")
1395 self.assertEqual(c.kind, None)
1396
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001397
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00001398class EndPositionTests(unittest.TestCase):
1399 """Tests for end position of AST nodes.
1400
1401 Testing end positions of nodes requires a bit of extra care
1402 because of how LL parsers work.
1403 """
1404 def _check_end_pos(self, ast_node, end_lineno, end_col_offset):
1405 self.assertEqual(ast_node.end_lineno, end_lineno)
1406 self.assertEqual(ast_node.end_col_offset, end_col_offset)
1407
1408 def _check_content(self, source, ast_node, content):
1409 self.assertEqual(ast.get_source_segment(source, ast_node), content)
1410
1411 def _parse_value(self, s):
1412 # Use duck-typing to support both single expression
1413 # and a right hand side of an assignment statement.
1414 return ast.parse(s).body[0].value
1415
1416 def test_lambda(self):
1417 s = 'lambda x, *y: None'
1418 lam = self._parse_value(s)
1419 self._check_content(s, lam.body, 'None')
1420 self._check_content(s, lam.args.args[0], 'x')
1421 self._check_content(s, lam.args.vararg, 'y')
1422
1423 def test_func_def(self):
1424 s = dedent('''
1425 def func(x: int,
1426 *args: str,
1427 z: float = 0,
1428 **kwargs: Any) -> bool:
1429 return True
1430 ''').strip()
1431 fdef = ast.parse(s).body[0]
1432 self._check_end_pos(fdef, 5, 15)
1433 self._check_content(s, fdef.body[0], 'return True')
1434 self._check_content(s, fdef.args.args[0], 'x: int')
1435 self._check_content(s, fdef.args.args[0].annotation, 'int')
1436 self._check_content(s, fdef.args.kwarg, 'kwargs: Any')
1437 self._check_content(s, fdef.args.kwarg.annotation, 'Any')
1438
1439 def test_call(self):
1440 s = 'func(x, y=2, **kw)'
1441 call = self._parse_value(s)
1442 self._check_content(s, call.func, 'func')
1443 self._check_content(s, call.keywords[0].value, '2')
1444 self._check_content(s, call.keywords[1].value, 'kw')
1445
1446 def test_call_noargs(self):
1447 s = 'x[0]()'
1448 call = self._parse_value(s)
1449 self._check_content(s, call.func, 'x[0]')
1450 self._check_end_pos(call, 1, 6)
1451
1452 def test_class_def(self):
1453 s = dedent('''
1454 class C(A, B):
1455 x: int = 0
1456 ''').strip()
1457 cdef = ast.parse(s).body[0]
1458 self._check_end_pos(cdef, 2, 14)
1459 self._check_content(s, cdef.bases[1], 'B')
1460 self._check_content(s, cdef.body[0], 'x: int = 0')
1461
1462 def test_class_kw(self):
1463 s = 'class S(metaclass=abc.ABCMeta): pass'
1464 cdef = ast.parse(s).body[0]
1465 self._check_content(s, cdef.keywords[0].value, 'abc.ABCMeta')
1466
1467 def test_multi_line_str(self):
1468 s = dedent('''
1469 x = """Some multi-line text.
1470
1471 It goes on starting from same indent."""
1472 ''').strip()
1473 assign = ast.parse(s).body[0]
1474 self._check_end_pos(assign, 3, 40)
1475 self._check_end_pos(assign.value, 3, 40)
1476
1477 def test_continued_str(self):
1478 s = dedent('''
1479 x = "first part" \\
1480 "second part"
1481 ''').strip()
1482 assign = ast.parse(s).body[0]
1483 self._check_end_pos(assign, 2, 13)
1484 self._check_end_pos(assign.value, 2, 13)
1485
1486 def test_suites(self):
1487 # We intentionally put these into the same string to check
1488 # that empty lines are not part of the suite.
1489 s = dedent('''
1490 while True:
1491 pass
1492
1493 if one():
1494 x = None
1495 elif other():
1496 y = None
1497 else:
1498 z = None
1499
1500 for x, y in stuff:
1501 assert True
1502
1503 try:
1504 raise RuntimeError
1505 except TypeError as e:
1506 pass
1507
1508 pass
1509 ''').strip()
1510 mod = ast.parse(s)
1511 while_loop = mod.body[0]
1512 if_stmt = mod.body[1]
1513 for_loop = mod.body[2]
1514 try_stmt = mod.body[3]
1515 pass_stmt = mod.body[4]
1516
1517 self._check_end_pos(while_loop, 2, 8)
1518 self._check_end_pos(if_stmt, 9, 12)
1519 self._check_end_pos(for_loop, 12, 15)
1520 self._check_end_pos(try_stmt, 17, 8)
1521 self._check_end_pos(pass_stmt, 19, 4)
1522
1523 self._check_content(s, while_loop.test, 'True')
1524 self._check_content(s, if_stmt.body[0], 'x = None')
1525 self._check_content(s, if_stmt.orelse[0].test, 'other()')
1526 self._check_content(s, for_loop.target, 'x, y')
1527 self._check_content(s, try_stmt.body[0], 'raise RuntimeError')
1528 self._check_content(s, try_stmt.handlers[0].type, 'TypeError')
1529
1530 def test_fstring(self):
1531 s = 'x = f"abc {x + y} abc"'
1532 fstr = self._parse_value(s)
1533 binop = fstr.values[1].value
1534 self._check_content(s, binop, 'x + y')
1535
1536 def test_fstring_multi_line(self):
1537 s = dedent('''
1538 f"""Some multi-line text.
1539 {
1540 arg_one
1541 +
1542 arg_two
1543 }
1544 It goes on..."""
1545 ''').strip()
1546 fstr = self._parse_value(s)
1547 binop = fstr.values[1].value
1548 self._check_end_pos(binop, 5, 7)
1549 self._check_content(s, binop.left, 'arg_one')
1550 self._check_content(s, binop.right, 'arg_two')
1551
1552 def test_import_from_multi_line(self):
1553 s = dedent('''
1554 from x.y.z import (
1555 a, b, c as c
1556 )
1557 ''').strip()
1558 imp = ast.parse(s).body[0]
1559 self._check_end_pos(imp, 3, 1)
1560
1561 def test_slices(self):
1562 s1 = 'f()[1, 2] [0]'
1563 s2 = 'x[ a.b: c.d]'
1564 sm = dedent('''
1565 x[ a.b: f () ,
1566 g () : c.d
1567 ]
1568 ''').strip()
1569 i1, i2, im = map(self._parse_value, (s1, s2, sm))
1570 self._check_content(s1, i1.value, 'f()[1, 2]')
1571 self._check_content(s1, i1.value.slice.value, '1, 2')
1572 self._check_content(s2, i2.slice.lower, 'a.b')
1573 self._check_content(s2, i2.slice.upper, 'c.d')
1574 self._check_content(sm, im.slice.dims[0].upper, 'f ()')
1575 self._check_content(sm, im.slice.dims[1].lower, 'g ()')
1576 self._check_end_pos(im, 3, 3)
1577
1578 def test_binop(self):
1579 s = dedent('''
1580 (1 * 2 + (3 ) +
1581 4
1582 )
1583 ''').strip()
1584 binop = self._parse_value(s)
1585 self._check_end_pos(binop, 2, 6)
1586 self._check_content(s, binop.right, '4')
1587 self._check_content(s, binop.left, '1 * 2 + (3 )')
1588 self._check_content(s, binop.left.right, '3')
1589
1590 def test_boolop(self):
1591 s = dedent('''
1592 if (one_condition and
1593 (other_condition or yet_another_one)):
1594 pass
1595 ''').strip()
1596 bop = ast.parse(s).body[0].test
1597 self._check_end_pos(bop, 2, 44)
1598 self._check_content(s, bop.values[1],
1599 'other_condition or yet_another_one')
1600
1601 def test_tuples(self):
1602 s1 = 'x = () ;'
1603 s2 = 'x = 1 , ;'
1604 s3 = 'x = (1 , 2 ) ;'
1605 sm = dedent('''
1606 x = (
1607 a, b,
1608 )
1609 ''').strip()
1610 t1, t2, t3, tm = map(self._parse_value, (s1, s2, s3, sm))
1611 self._check_content(s1, t1, '()')
1612 self._check_content(s2, t2, '1 ,')
1613 self._check_content(s3, t3, '(1 , 2 )')
1614 self._check_end_pos(tm, 3, 1)
1615
1616 def test_attribute_spaces(self):
1617 s = 'func(x. y .z)'
1618 call = self._parse_value(s)
1619 self._check_content(s, call, s)
1620 self._check_content(s, call.args[0], 'x. y .z')
1621
1622 def test_displays(self):
1623 s1 = '[{}, {1, }, {1, 2,} ]'
1624 s2 = '{a: b, f (): g () ,}'
1625 c1 = self._parse_value(s1)
1626 c2 = self._parse_value(s2)
1627 self._check_content(s1, c1.elts[0], '{}')
1628 self._check_content(s1, c1.elts[1], '{1, }')
1629 self._check_content(s1, c1.elts[2], '{1, 2,}')
1630 self._check_content(s2, c2.keys[1], 'f ()')
1631 self._check_content(s2, c2.values[1], 'g ()')
1632
1633 def test_comprehensions(self):
1634 s = dedent('''
1635 x = [{x for x, y in stuff
1636 if cond.x} for stuff in things]
1637 ''').strip()
1638 cmp = self._parse_value(s)
1639 self._check_end_pos(cmp, 2, 37)
1640 self._check_content(s, cmp.generators[0].iter, 'things')
1641 self._check_content(s, cmp.elt.generators[0].iter, 'stuff')
1642 self._check_content(s, cmp.elt.generators[0].ifs[0], 'cond.x')
1643 self._check_content(s, cmp.elt.generators[0].target, 'x, y')
1644
1645 def test_yield_await(self):
1646 s = dedent('''
1647 async def f():
1648 yield x
1649 await y
1650 ''').strip()
1651 fdef = ast.parse(s).body[0]
1652 self._check_content(s, fdef.body[0].value, 'yield x')
1653 self._check_content(s, fdef.body[1].value, 'await y')
1654
1655 def test_source_segment_multi(self):
1656 s_orig = dedent('''
1657 x = (
1658 a, b,
1659 ) + ()
1660 ''').strip()
1661 s_tuple = dedent('''
1662 (
1663 a, b,
1664 )
1665 ''').strip()
1666 binop = self._parse_value(s_orig)
1667 self.assertEqual(ast.get_source_segment(s_orig, binop.left), s_tuple)
1668
1669 def test_source_segment_padded(self):
1670 s_orig = dedent('''
1671 class C:
1672 def fun(self) -> None:
1673 "ЖЖЖЖЖ"
1674 ''').strip()
1675 s_method = ' def fun(self) -> None:\n' \
1676 ' "ЖЖЖЖЖ"'
1677 cdef = ast.parse(s_orig).body[0]
1678 self.assertEqual(ast.get_source_segment(s_orig, cdef.body[0], padded=True),
1679 s_method)
1680
1681 def test_source_segment_endings(self):
1682 s = 'v = 1\r\nw = 1\nx = 1\n\ry = 1\rz = 1\r\n'
1683 v, w, x, y, z = ast.parse(s).body
1684 self._check_content(s, v, 'v = 1')
1685 self._check_content(s, w, 'w = 1')
1686 self._check_content(s, x, 'x = 1')
1687 self._check_content(s, y, 'y = 1')
1688 self._check_content(s, z, 'z = 1')
1689
1690 def test_source_segment_tabs(self):
1691 s = dedent('''
1692 class C:
1693 \t\f def fun(self) -> None:
1694 \t\f pass
1695 ''').strip()
1696 s_method = ' \t\f def fun(self) -> None:\n' \
1697 ' \t\f pass'
1698
1699 cdef = ast.parse(s).body[0]
1700 self.assertEqual(ast.get_source_segment(s, cdef.body[0], padded=True), s_method)
1701
1702
Miss Islington (bot)522a3942019-08-26 00:43:33 -07001703class NodeVisitorTests(unittest.TestCase):
1704 def test_old_constant_nodes(self):
1705 class Visitor(ast.NodeVisitor):
1706 def visit_Num(self, node):
1707 log.append((node.lineno, 'Num', node.n))
1708 def visit_Str(self, node):
1709 log.append((node.lineno, 'Str', node.s))
1710 def visit_Bytes(self, node):
1711 log.append((node.lineno, 'Bytes', node.s))
1712 def visit_NameConstant(self, node):
1713 log.append((node.lineno, 'NameConstant', node.value))
1714 def visit_Ellipsis(self, node):
1715 log.append((node.lineno, 'Ellipsis', ...))
1716 mod = ast.parse(dedent('''\
1717 i = 42
1718 f = 4.25
1719 c = 4.25j
1720 s = 'string'
1721 b = b'bytes'
1722 t = True
1723 n = None
1724 e = ...
1725 '''))
1726 visitor = Visitor()
1727 log = []
1728 with warnings.catch_warnings(record=True) as wlog:
1729 warnings.filterwarnings('always', '', PendingDeprecationWarning)
1730 visitor.visit(mod)
1731 self.assertEqual(log, [
1732 (1, 'Num', 42),
1733 (2, 'Num', 4.25),
1734 (3, 'Num', 4.25j),
1735 (4, 'Str', 'string'),
1736 (5, 'Bytes', b'bytes'),
1737 (6, 'NameConstant', True),
1738 (7, 'NameConstant', None),
1739 (8, 'Ellipsis', ...),
1740 ])
1741 self.assertEqual([str(w.message) for w in wlog], [
1742 'visit_Num is deprecated; add visit_Constant',
1743 'visit_Num is deprecated; add visit_Constant',
1744 'visit_Num is deprecated; add visit_Constant',
1745 'visit_Str is deprecated; add visit_Constant',
1746 'visit_Bytes is deprecated; add visit_Constant',
1747 'visit_NameConstant is deprecated; add visit_Constant',
1748 'visit_NameConstant is deprecated; add visit_Constant',
1749 'visit_Ellipsis is deprecated; add visit_Constant',
1750 ])
1751
1752
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001753def main():
1754 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001755 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001756 if sys.argv[1:] == ['-g']:
1757 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
1758 (eval_tests, "eval")):
1759 print(kind+"_results = [")
Victor Stinnerf0891962016-02-08 17:15:21 +01001760 for statement in statements:
1761 tree = ast.parse(statement, "?", kind)
1762 print("%r," % (to_tuple(tree),))
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001763 print("]")
1764 print("main()")
1765 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001766 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +00001767
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001768#### EVERYTHING BELOW IS GENERATED BY python Lib/test/test_ast.py -g #####
Tim Peters400cbc32006-02-28 18:44:41 +00001769exec_results = [
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001770('Module', [('Expr', (1, 0), ('Constant', (1, 0), None, None))], []),
1771('Module', [('Expr', (1, 0), ('Constant', (1, 0), 'module docstring', None))], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001772('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 9))], [], None, None)], []),
1773('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (1, 9), ('Constant', (1, 9), 'function docstring', None))], [], None, None)], []),
Miss Islington (bot)cf9a63c2019-07-14 16:49:52 -07001774('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [('arg', (1, 6), 'a', None, None)], None, [], [], None, []), [('Pass', (1, 10))], [], None, None)], []),
1775('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [('arg', (1, 6), 'a', None, None)], None, [], [], None, [('Constant', (1, 8), 0, None)]), [('Pass', (1, 12))], [], None, None)], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001776('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], ('arg', (1, 7), 'args', None, None), [], [], None, []), [('Pass', (1, 14))], [], None, None)], []),
1777('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], ('arg', (1, 8), 'kwargs', None, None), []), [('Pass', (1, 17))], [], None, None)], []),
Miss Islington (bot)cf9a63c2019-07-14 16:49:52 -07001778('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [('arg', (1, 6), 'a', None, None), ('arg', (1, 9), 'b', None, None), ('arg', (1, 14), 'c', None, None), ('arg', (1, 22), 'd', None, None), ('arg', (1, 28), 'e', None, None)], ('arg', (1, 35), 'args', None, None), [('arg', (1, 41), 'f', None, None)], [('Constant', (1, 43), 42, None)], ('arg', (1, 49), 'kwargs', None, None), [('Constant', (1, 11), 1, None), ('Constant', (1, 16), None, None), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [('Expr', (1, 58), ('Constant', (1, 58), 'doc for f()', None))], [], None, None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001779('Module', [('ClassDef', (1, 0), 'C', [], [], [('Pass', (1, 8))], [])], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001780('Module', [('ClassDef', (1, 0), 'C', [], [], [('Expr', (1, 9), ('Constant', (1, 9), 'docstring for class C', None))], [])], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001781('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], [('Pass', (1, 17))], [])], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001782('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Return', (1, 8), ('Constant', (1, 15), 1, None))], [], None, None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001783('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001784('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Constant', (1, 4), 1, None), None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001785('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 0), 'a', ('Store',)), ('Name', (1, 2), 'b', ('Store',))], ('Store',))], ('Name', (1, 6), 'c', ('Load',)), None)], []),
1786('Module', [('Assign', (1, 0), [('Tuple', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)), None)], []),
1787('Module', [('Assign', (1, 0), [('List', (1, 0), [('Name', (1, 1), 'a', ('Store',)), ('Name', (1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 8), 'c', ('Load',)), None)], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001788('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Constant', (1, 5), 1, None))], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001789('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [], None)], []),
1790('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])], []),
1791('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])], []),
Miss Islington (bot)3b18b172019-12-13 08:21:54 -08001792('Module', [('If', (1, 0), ('Name', (1, 3), 'a', ('Load',)), [('Pass', (2, 2))], [('If', (3, 0), ('Name', (3, 5), 'b', ('Load',)), [('Pass', (4, 2))], [])])], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001793('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))], None)], []),
1794('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',))), ('withitem', ('Name', (1, 13), 'z', ('Load',)), ('Name', (1, 18), 'q', ('Store',)))], [('Pass', (1, 21))], None)], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001795('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Constant', (1, 16), 'string', None)], []), None)], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001796('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])], []),
1797('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])], []),
1798('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)], []),
1799('Module', [('Import', (1, 0), [('alias', 'sys', None)])], []),
1800('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)], []),
1801('Module', [('Global', (1, 0), ['v'])], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001802('Module', [('Expr', (1, 0), ('Constant', (1, 0), 1, None))], []),
Guido van Rossumdcfcd142019-01-31 03:40:27 -08001803('Module', [('Pass', (1, 0))], []),
1804('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Break', (1, 11))], [], None)], []),
1805('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Continue', (1, 11))], [], None)], []),
1806('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 4), 'a', ('Store',)), ('Name', (1, 6), 'b', ('Store',))], ('Store',)), ('Name', (1, 11), 'c', ('Load',)), [('Pass', (1, 14))], [], None)], []),
1807('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 5), 'a', ('Store',)), ('Name', (1, 7), 'b', ('Store',))], ('Store',)), ('Name', (1, 13), 'c', ('Load',)), [('Pass', (1, 16))], [], None)], []),
1808('Module', [('For', (1, 0), ('List', (1, 4), [('Name', (1, 5), 'a', ('Store',)), ('Name', (1, 7), 'b', ('Store',))], ('Store',)), ('Name', (1, 13), 'c', ('Load',)), [('Pass', (1, 16))], [], None)], []),
1809('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 0), ('Tuple', (2, 4), [('Name', (3, 4), 'Aa', ('Load',)), ('Name', (5, 7), 'Bb', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (8, 4), [('Name', (8, 4), 'Aa', ('Store',)), ('Name', (10, 4), 'Bb', ('Store',))], ('Store',)), ('Name', (10, 10), 'Cc', ('Load',)), [], 0)]))], []),
1810('Module', [('Expr', (1, 0), ('DictComp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Name', (1, 11), 'w', ('Store',)), ('Name', (1, 16), 'x', ('Load',)), [], 0), ('comprehension', ('Name', (1, 22), 'm', ('Store',)), ('Name', (1, 27), 'p', ('Load',)), [('Name', (1, 32), 'g', ('Load',))], 0)]))], []),
1811('Module', [('Expr', (1, 0), ('DictComp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'v', ('Store',)), ('Name', (1, 13), 'w', ('Store',))], ('Store',)), ('Name', (1, 18), 'x', ('Load',)), [], 0)]))], []),
1812('Module', [('Expr', (1, 0), ('SetComp', (1, 0), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 12), 'x', ('Load',)), [('Name', (1, 17), 'g', ('Load',))], 0)]))], []),
1813('Module', [('Expr', (1, 0), ('SetComp', (1, 0), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Tuple', (1, 7), [('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 9), 'm', ('Store',))], ('Store',)), ('Name', (1, 14), 'x', ('Load',)), [], 0)]))], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001814('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1), ('Constant', (2, 1), 'async function', None)), ('Expr', (3, 1), ('Await', (3, 1), ('Call', (3, 7), ('Name', (3, 7), 'something', ('Load',)), [], [])))], [], None, None)], []),
1815('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncFor', (2, 1), ('Name', (2, 11), 'e', ('Store',)), ('Name', (2, 16), 'i', ('Load',)), [('Expr', (2, 19), ('Constant', (2, 19), 1, None))], [('Expr', (3, 7), ('Constant', (3, 7), 2, None))], None)], [], None, None)], []),
1816('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncWith', (2, 1), [('withitem', ('Name', (2, 12), 'a', ('Load',)), ('Name', (2, 17), 'b', ('Store',)))], [('Expr', (2, 20), ('Constant', (2, 20), 1, None))], None)], [], None, None)], []),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001817('Module', [('Expr', (1, 0), ('Dict', (1, 0), [None, ('Constant', (1, 10), 2, None)], [('Dict', (1, 3), [('Constant', (1, 4), 1, None)], [('Constant', (1, 6), 2, None)]), ('Constant', (1, 12), 3, None)]))], []),
1818('Module', [('Expr', (1, 0), ('Set', (1, 0), [('Starred', (1, 1), ('Set', (1, 2), [('Constant', (1, 3), 1, None), ('Constant', (1, 6), 2, None)]), ('Load',)), ('Constant', (1, 10), 3, None)]))], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001819('Module', [('AsyncFunctionDef', (1, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1), ('ListComp', (2, 1), ('Name', (2, 2), 'i', ('Load',)), [('comprehension', ('Name', (2, 14), 'b', ('Store',)), ('Name', (2, 19), 'c', ('Load',)), [], 1)]))], [], None, None)], []),
Miss Skeleton (bot)ba3a5662019-10-26 07:06:40 -07001820('Module', [('FunctionDef', (4, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 1), ('Name', (2, 1), 'deco2', ('Load',)), [], []), ('Call', (3, 1), ('Name', (3, 1), 'deco3', ('Load',)), [('Constant', (3, 7), 1, None)], [])], None, None)], []),
1821('Module', [('AsyncFunctionDef', (4, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 15))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 1), ('Name', (2, 1), 'deco2', ('Load',)), [], []), ('Call', (3, 1), ('Name', (3, 1), 'deco3', ('Load',)), [('Constant', (3, 7), 1, None)], [])], None, None)], []),
1822('Module', [('ClassDef', (4, 0), 'C', [], [], [('Pass', (4, 9))], [('Name', (1, 1), 'deco1', ('Load',)), ('Call', (2, 1), ('Name', (2, 1), 'deco2', ('Load',)), [], []), ('Call', (3, 1), ('Name', (3, 1), 'deco3', ('Load',)), [('Constant', (3, 7), 1, None)], [])])], []),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001823('Module', [('FunctionDef', (2, 0), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9))], [('Call', (1, 1), ('Name', (1, 1), 'deco', ('Load',)), [('GeneratorExp', (1, 5), ('Name', (1, 6), 'a', ('Load',)), [('comprehension', ('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 17), 'b', ('Load',)), [], 0)])], [])], None, None)], []),
Pablo Galindo0c9258a2019-03-18 13:51:53 +00001824('Module', [('Expr', (1, 0), ('NamedExpr', (1, 1), ('Name', (1, 1), 'a', ('Store',)), ('Constant', (1, 6), 1, None)))], []),
Miss Islington (bot)cf9a63c2019-07-14 16:49:52 -07001825('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [], None, [], [], None, []), [('Pass', (1, 14))], [], None, None)], []),
1826('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 12), 'c', None, None), ('arg', (1, 15), 'd', None, None), ('arg', (1, 18), 'e', None, None)], None, [], [], None, []), [('Pass', (1, 22))], [], None, None)], []),
1827('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 12), 'c', None, None)], None, [('arg', (1, 18), 'd', None, None), ('arg', (1, 21), 'e', None, None)], [None, None], None, []), [('Pass', (1, 25))], [], None, None)], []),
1828('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 12), 'c', None, None)], None, [('arg', (1, 18), 'd', None, None), ('arg', (1, 21), 'e', None, None)], [None, None], ('arg', (1, 26), 'kwargs', None, None), []), [('Pass', (1, 35))], [], None, None)], []),
1829('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [], None, [], [], None, [('Constant', (1, 8), 1, None)]), [('Pass', (1, 16))], [], None, None)], []),
1830('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None), ('arg', (1, 19), 'c', None, None)], None, [], [], None, [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None), ('Constant', (1, 21), 4, None)]), [('Pass', (1, 25))], [], None, None)], []),
1831('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [('Constant', (1, 24), 4, None)], None, [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 28))], [], None, None)], []),
1832('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [None], None, [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 26))], [], None, None)], []),
1833('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [('Constant', (1, 24), 4, None)], ('arg', (1, 29), 'kwargs', None, None), [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 38))], [], None, None)], []),
1834('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None, None)], [('arg', (1, 14), 'b', None, None)], None, [('arg', (1, 22), 'c', None, None)], [None], ('arg', (1, 27), 'kwargs', None, None), [('Constant', (1, 8), 1, None), ('Constant', (1, 16), 2, None)]), [('Pass', (1, 36))], [], None, None)], []),
Tim Peters400cbc32006-02-28 18:44:41 +00001835]
1836single_results = [
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001837('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Constant', (1, 0), 1, None), ('Add',), ('Constant', (1, 2), 2, None)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001838]
1839eval_results = [
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001840('Expression', ('Constant', (1, 0), None, None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001841('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1842('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1843('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01001844('Expression', ('Lambda', (1, 0), ('arguments', [], [], None, [], [], None, []), ('Constant', (1, 7), None, None))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001845('Expression', ('Dict', (1, 0), [('Constant', (1, 2), 1, None)], [('Constant', (1, 4), 2, None)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001846('Expression', ('Dict', (1, 0), [], [])),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001847('Expression', ('Set', (1, 0), [('Constant', (1, 1), None, None)])),
1848('Expression', ('Dict', (1, 0), [('Constant', (2, 6), 1, None)], [('Constant', (4, 10), 2, None)])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001849('Expression', ('ListComp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1850('Expression', ('GeneratorExp', (1, 0), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1851('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1852('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1853('Expression', ('ListComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1854('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1855('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1856('Expression', ('SetComp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1857('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [], 0)])),
1858('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
1859('Expression', ('GeneratorExp', (1, 0), ('Tuple', (1, 1), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('List', (1, 11), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)])),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001860('Expression', ('Compare', (1, 0), ('Constant', (1, 0), 1, None), [('Lt',), ('Lt',)], [('Constant', (1, 4), 2, None), ('Constant', (1, 8), 3, None)])),
1861('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Constant', (1, 2), 1, None), ('Constant', (1, 4), 2, None), ('Starred', (1, 10), ('Name', (1, 11), 'd', ('Load',)), ('Load',))], [('keyword', 'c', ('Constant', (1, 8), 3, None)), ('keyword', None, ('Name', (1, 15), 'e', ('Load',)))])),
Serhiy Storchakab619b092018-11-27 09:40:29 +02001862('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('GeneratorExp', (1, 1), ('Name', (1, 2), 'a', ('Load',)), [('comprehension', ('Name', (1, 8), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Load',)), [], 0)])], [])),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001863('Expression', ('Constant', (1, 0), 10, None)),
1864('Expression', ('Constant', (1, 0), 'string', None)),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001865('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1866('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001867('Expression', ('Name', (1, 0), 'v', ('Load',))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001868('Expression', ('List', (1, 0), [('Constant', (1, 1), 1, None), ('Constant', (1, 3), 2, None), ('Constant', (1, 5), 3, None)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001869('Expression', ('List', (1, 0), [], ('Load',))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001870('Expression', ('Tuple', (1, 0), [('Constant', (1, 0), 1, None), ('Constant', (1, 2), 2, None), ('Constant', (1, 4), 3, None)], ('Load',))),
1871('Expression', ('Tuple', (1, 0), [('Constant', (1, 1), 1, None), ('Constant', (1, 3), 2, None), ('Constant', (1, 5), 3, None)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001872('Expression', ('Tuple', (1, 0), [], ('Load',))),
Guido van Rossum10f8ce62019-03-13 13:00:46 -07001873('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Constant', (1, 12), 1, None), ('Constant', (1, 14), 2, None), None), ('Load',))], [])),
Tim Peters400cbc32006-02-28 18:44:41 +00001874]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001875main()