blob: aa53503e3b5d8a43d8ccf41ef7a303db979a67f1 [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
Benjamin Peterson9ed37432012-07-08 11:13:36 -07006import weakref
7
8from test import support
Tim Peters400cbc32006-02-28 18:44:41 +00009
10def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +000011 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +000012 return t
13 elif isinstance(t, list):
14 return [to_tuple(e) for e in t]
15 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000016 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
17 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000018 if t._fields is None:
19 return tuple(result)
20 for f in t._fields:
21 result.append(to_tuple(getattr(t, f)))
22 return tuple(result)
23
Neal Norwitzee9b10a2008-03-31 05:29:39 +000024
Tim Peters400cbc32006-02-28 18:44:41 +000025# These tests are compiled through "exec"
Ezio Melotti85a86292013-08-17 16:57:41 +030026# There should be at least one test per statement
Tim Peters400cbc32006-02-28 18:44:41 +000027exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050028 # None
29 "None",
INADA Naokicb41b272017-02-23 00:31:59 +090030 # Module docstring
31 "'module docstring'",
Tim Peters400cbc32006-02-28 18:44:41 +000032 # FunctionDef
33 "def f(): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090034 # FunctionDef with docstring
35 "def f(): 'function docstring'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050036 # FunctionDef with arg
37 "def f(a): pass",
38 # FunctionDef with arg and default value
39 "def f(a=0): pass",
40 # FunctionDef with varargs
41 "def f(*args): pass",
42 # FunctionDef with kwargs
43 "def f(**kwargs): pass",
INADA Naokicb41b272017-02-23 00:31:59 +090044 # FunctionDef with all kind of args and docstring
45 "def f(a, b=1, c=None, d=[], e={}, *args, f=42, **kwargs): 'doc for f()'",
Tim Peters400cbc32006-02-28 18:44:41 +000046 # ClassDef
47 "class C:pass",
INADA Naokicb41b272017-02-23 00:31:59 +090048 # ClassDef with docstring
49 "class C: 'docstring for class C'",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050050 # ClassDef, new style class
51 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000052 # Return
53 "def f():return 1",
54 # Delete
55 "del v",
56 # Assign
57 "v = 1",
58 # AugAssign
59 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000060 # For
61 "for v in v:pass",
62 # While
63 "while v:pass",
64 # If
65 "if v:pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050066 # With
67 "with x as y: pass",
68 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000069 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000070 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000071 # TryExcept
72 "try:\n pass\nexcept Exception:\n pass",
73 # TryFinally
74 "try:\n pass\nfinally:\n pass",
75 # Assert
76 "assert v",
77 # Import
78 "import sys",
79 # ImportFrom
80 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000081 # Global
82 "global v",
83 # Expr
84 "1",
85 # Pass,
86 "pass",
87 # Break
Yury Selivanovb3d53132015-09-01 16:10:49 -040088 "for v in v:break",
Tim Peters400cbc32006-02-28 18:44:41 +000089 # Continue
Yury Selivanovb3d53132015-09-01 16:10:49 -040090 "for v in v:continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000091 # for statements with naked tuples (see http://bugs.python.org/issue6704)
92 "for a,b in c: pass",
93 "[(a,b) for a,b in c]",
94 "((a,b) for a,b in c)",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050095 "((a,b) for (a,b) in c)",
96 # Multiline generator expression (test for .lineno & .col_offset)
97 """(
98 (
99 Aa
100 ,
101 Bb
102 )
103 for
104 Aa
105 ,
106 Bb in Cc
107 )""",
108 # dictcomp
109 "{a : b for w in x for m in p if g}",
110 # dictcomp with naked tuple
111 "{a : b for v,w in x}",
112 # setcomp
113 "{r for l in x if g}",
114 # setcomp with naked tuple
115 "{r for l,m in x}",
Yury Selivanov75445082015-05-11 22:57:16 -0400116 # AsyncFunctionDef
INADA Naokicb41b272017-02-23 00:31:59 +0900117 "async def f():\n 'async function'\n await something()",
Yury Selivanov75445082015-05-11 22:57:16 -0400118 # AsyncFor
119 "async def f():\n async for e in i: 1\n else: 2",
120 # AsyncWith
121 "async def f():\n async with a as b: 1",
Yury Selivanovb3d53132015-09-01 16:10:49 -0400122 # PEP 448: Additional Unpacking Generalizations
123 "{**{1:2}, 2:3}",
124 "{*{1, 2}, 3}",
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700125 # Asynchronous comprehensions
126 "async def f():\n [i async for b in c]",
Tim Peters400cbc32006-02-28 18:44:41 +0000127]
128
129# These are compiled through "single"
130# because of overlap with "eval", it just tests what
131# can't be tested with "eval"
132single_tests = [
133 "1+2"
134]
135
136# These are compiled through "eval"
137# It should test all expressions
138eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500139 # None
140 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000141 # BoolOp
142 "a and b",
143 # BinOp
144 "a + b",
145 # UnaryOp
146 "not v",
147 # Lambda
148 "lambda:None",
149 # Dict
150 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500151 # Empty dict
152 "{}",
153 # Set
154 "{None,}",
155 # Multiline dict (test for .lineno & .col_offset)
156 """{
157 1
158 :
159 2
160 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000161 # ListComp
162 "[a for b in c if d]",
163 # GeneratorExp
164 "(a for b in c if d)",
165 # Yield - yield expressions can't work outside a function
166 #
167 # Compare
168 "1 < 2 < 3",
169 # Call
170 "f(1,2,c=3,*d,**e)",
Tim Peters400cbc32006-02-28 18:44:41 +0000171 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000172 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000173 # Str
174 "'string'",
175 # Attribute
176 "a.b",
177 # Subscript
178 "a[b:c]",
179 # Name
180 "v",
181 # List
182 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500183 # Empty list
184 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000185 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000186 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500187 # Tuple
188 "(1,2,3)",
189 # Empty tuple
190 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000191 # Combination
192 "a.b.c.d(a.b[1:2])",
193
Tim Peters400cbc32006-02-28 18:44:41 +0000194]
195
196# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
197# excepthandler, arguments, keywords, alias
198
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000199class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000200
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500201 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000202 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000203 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000204 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000205 node_pos = (ast_node.lineno, ast_node.col_offset)
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500206 self.assertTrue(node_pos >= parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000207 parent_pos = (ast_node.lineno, ast_node.col_offset)
208 for name in ast_node._fields:
209 value = getattr(ast_node, name)
210 if isinstance(value, list):
211 for child in value:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500212 self._assertTrueorder(child, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000213 elif value is not None:
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500214 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000215
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500216 def test_AST_objects(self):
217 x = ast.AST()
218 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700219 x.foobar = 42
220 self.assertEqual(x.foobar, 42)
221 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500222
223 with self.assertRaises(AttributeError):
224 x.vararg
225
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500226 with self.assertRaises(TypeError):
227 # "_ast.AST constructor takes 0 positional arguments"
228 ast.AST(2)
229
Benjamin Peterson9ed37432012-07-08 11:13:36 -0700230 def test_AST_garbage_collection(self):
231 class X:
232 pass
233 a = ast.AST()
234 a.x = X()
235 a.x.a = a
236 ref = weakref.ref(a.x)
237 del a
238 support.gc_collect()
239 self.assertIsNone(ref())
240
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000241 def test_snippets(self):
242 for input, output, kind in ((exec_tests, exec_results, "exec"),
243 (single_tests, single_results, "single"),
244 (eval_tests, eval_results, "eval")):
245 for i, o in zip(input, output):
Yury Selivanovb3d53132015-09-01 16:10:49 -0400246 with self.subTest(action="parsing", input=i):
247 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
248 self.assertEqual(to_tuple(ast_tree), o)
249 self._assertTrueorder(ast_tree, (0, 0))
Victor Stinner15a30952016-02-08 22:45:06 +0100250 with self.subTest(action="compiling", input=i, kind=kind):
251 compile(ast_tree, "?", kind)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000252
Benjamin Peterson78565b22009-06-28 19:19:51 +0000253 def test_slice(self):
254 slc = ast.parse("x[::]").body[0].value.slice
255 self.assertIsNone(slc.upper)
256 self.assertIsNone(slc.lower)
257 self.assertIsNone(slc.step)
258
259 def test_from_import(self):
260 im = ast.parse("from . import y").body[0]
261 self.assertIsNone(im.module)
262
Benjamin Petersona4e4e352012-03-22 08:19:04 -0400263 def test_non_interned_future_from_ast(self):
264 mod = ast.parse("from __future__ import division")
265 self.assertIsInstance(mod.body[0], ast.ImportFrom)
266 mod.body[0].module = " __future__ ".strip()
267 compile(mod, "<test>", "exec")
268
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000269 def test_base_classes(self):
270 self.assertTrue(issubclass(ast.For, ast.stmt))
271 self.assertTrue(issubclass(ast.Name, ast.expr))
272 self.assertTrue(issubclass(ast.stmt, ast.AST))
273 self.assertTrue(issubclass(ast.expr, ast.AST))
274 self.assertTrue(issubclass(ast.comprehension, ast.AST))
275 self.assertTrue(issubclass(ast.Gt, ast.AST))
276
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500277 def test_field_attr_existence(self):
278 for name, item in ast.__dict__.items():
279 if isinstance(item, type) and name != 'AST' and name[0].isupper():
280 x = item()
281 if isinstance(x, ast.AST):
282 self.assertEqual(type(x._fields), tuple)
283
284 def test_arguments(self):
285 x = ast.arguments()
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500286 self.assertEqual(x._fields, ('args', 'vararg', 'kwonlyargs',
287 'kw_defaults', 'kwarg', 'defaults'))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500288
289 with self.assertRaises(AttributeError):
290 x.vararg
291
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700292 x = ast.arguments(*range(1, 7))
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500293 self.assertEqual(x.vararg, 2)
294
295 def test_field_attr_writable(self):
296 x = ast.Num()
297 # We can assign to _fields
298 x._fields = 666
299 self.assertEqual(x._fields, 666)
300
301 def test_classattrs(self):
302 x = ast.Num()
303 self.assertEqual(x._fields, ('n',))
304
305 with self.assertRaises(AttributeError):
306 x.n
307
308 x = ast.Num(42)
309 self.assertEqual(x.n, 42)
310
311 with self.assertRaises(AttributeError):
312 x.lineno
313
314 with self.assertRaises(AttributeError):
315 x.foobar
316
317 x = ast.Num(lineno=2)
318 self.assertEqual(x.lineno, 2)
319
320 x = ast.Num(42, lineno=0)
321 self.assertEqual(x.lineno, 0)
322 self.assertEqual(x._fields, ('n',))
323 self.assertEqual(x.n, 42)
324
325 self.assertRaises(TypeError, ast.Num, 1, 2)
326 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
327
328 def test_module(self):
329 body = [ast.Num(42)]
INADA Naokicb41b272017-02-23 00:31:59 +0900330 x = ast.Module(body, None)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500331 self.assertEqual(x.body, body)
332
INADA Naokicb41b272017-02-23 00:31:59 +0900333 def test_docstring(self):
334 body = [] # AST nodes having docstring must accept empty body
335 x = ast.Module(body, "module docstring")
336 self.assertEqual(x.docstring, "module docstring")
337
338 a = ast.arguments()
339 x = ast.FunctionDef("x", a, body, [], None, "func docstring")
340 self.assertEqual(x.docstring, "func docstring")
341
342 x = ast.AsyncFunctionDef("x", a, body, [], None, "async func docstring")
343 self.assertEqual(x.docstring, "async func docstring")
344
345 x = ast.ClassDef("x", [], [], body, [], "class docstring")
346 self.assertEqual(x.docstring, "class docstring")
347
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000348 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100349 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500350 x = ast.BinOp()
351 self.assertEqual(x._fields, ('left', 'op', 'right'))
352
353 # Random attribute allowed too
354 x.foobarbaz = 5
355 self.assertEqual(x.foobarbaz, 5)
356
357 n1 = ast.Num(1)
358 n3 = ast.Num(3)
359 addop = ast.Add()
360 x = ast.BinOp(n1, addop, n3)
361 self.assertEqual(x.left, n1)
362 self.assertEqual(x.op, addop)
363 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500364
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500365 x = ast.BinOp(1, 2, 3)
366 self.assertEqual(x.left, 1)
367 self.assertEqual(x.op, 2)
368 self.assertEqual(x.right, 3)
369
Georg Brandl0c77a822008-06-10 16:37:50 +0000370 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000371 self.assertEqual(x.left, 1)
372 self.assertEqual(x.op, 2)
373 self.assertEqual(x.right, 3)
374 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000375
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500376 # node raises exception when given too many arguments
377 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500378 # node raises exception when given too many arguments
379 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000380
381 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000382 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000383 self.assertEqual(x.left, 1)
384 self.assertEqual(x.op, 2)
385 self.assertEqual(x.right, 3)
386 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000387
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500388 # Random kwargs also allowed
389 x = ast.BinOp(1, 2, 3, foobarbaz=42)
390 self.assertEqual(x.foobarbaz, 42)
391
392 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000393 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000394 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500395 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000396
397 def test_pickling(self):
398 import pickle
399 mods = [pickle]
400 try:
401 import cPickle
402 mods.append(cPickle)
403 except ImportError:
404 pass
405 protocols = [0, 1, 2]
406 for mod in mods:
407 for protocol in protocols:
408 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
409 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000410 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000411
Benjamin Peterson5b066812010-11-20 01:38:49 +0000412 def test_invalid_sum(self):
413 pos = dict(lineno=2, col_offset=3)
INADA Naokicb41b272017-02-23 00:31:59 +0900414 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], "doc")
Benjamin Peterson5b066812010-11-20 01:38:49 +0000415 with self.assertRaises(TypeError) as cm:
416 compile(m, "<test>", "exec")
417 self.assertIn("but got <_ast.expr", str(cm.exception))
418
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500419 def test_invalid_identitifer(self):
INADA Naokicb41b272017-02-23 00:31:59 +0900420 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))], None)
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500421 ast.fix_missing_locations(m)
422 with self.assertRaises(TypeError) as cm:
423 compile(m, "<test>", "exec")
424 self.assertIn("identifier must be of type str", str(cm.exception))
425
Mark Dickinsonded35ae2012-11-25 14:36:26 +0000426 def test_empty_yield_from(self):
427 # Issue 16546: yield from value is not optional.
428 empty_yield_from = ast.parse("def f():\n yield from g()")
429 empty_yield_from.body[0].body[0].value.value = None
430 with self.assertRaises(ValueError) as cm:
431 compile(empty_yield_from, "<test>", "exec")
432 self.assertIn("field value is required", str(cm.exception))
433
Oren Milman7dc46d82017-09-30 20:16:24 +0300434 @support.cpython_only
435 def test_issue31592(self):
436 # There shouldn't be an assertion failure in case of a bad
437 # unicodedata.normalize().
438 import unicodedata
439 def bad_normalize(*args):
440 return None
441 with support.swap_attr(unicodedata, 'normalize', bad_normalize):
442 self.assertRaises(TypeError, ast.parse, '\u03D5')
443
Georg Brandl0c77a822008-06-10 16:37:50 +0000444
445class ASTHelpers_Test(unittest.TestCase):
446
447 def test_parse(self):
448 a = ast.parse('foo(1 + 1)')
449 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
450 self.assertEqual(ast.dump(a), ast.dump(b))
451
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400452 def test_parse_in_error(self):
453 try:
454 1/0
455 except Exception:
Benjamin Petersonbd0df502012-09-02 15:04:51 -0400456 with self.assertRaises(SyntaxError) as e:
457 ast.literal_eval(r"'\U'")
458 self.assertIsNotNone(e.exception.__context__)
Benjamin Peterson2e2c9032012-09-02 14:23:15 -0400459
Georg Brandl0c77a822008-06-10 16:37:50 +0000460 def test_dump(self):
461 node = ast.parse('spam(eggs, "and cheese")')
462 self.assertEqual(ast.dump(node),
463 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
464 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
INADA Naokicb41b272017-02-23 00:31:59 +0900465 "keywords=[]))], docstring=None)"
Georg Brandl0c77a822008-06-10 16:37:50 +0000466 )
467 self.assertEqual(ast.dump(node, annotate_fields=False),
468 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
INADA Naokicb41b272017-02-23 00:31:59 +0900469 "Str('and cheese')], []))], None)"
Georg Brandl0c77a822008-06-10 16:37:50 +0000470 )
471 self.assertEqual(ast.dump(node, include_attributes=True),
472 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
473 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
474 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400475 "col_offset=11)], keywords=[], "
INADA Naokicb41b272017-02-23 00:31:59 +0900476 "lineno=1, col_offset=0), lineno=1, col_offset=0)], docstring=None)"
Georg Brandl0c77a822008-06-10 16:37:50 +0000477 )
478
479 def test_copy_location(self):
480 src = ast.parse('1 + 1', mode='eval')
481 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
482 self.assertEqual(ast.dump(src, include_attributes=True),
483 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
484 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
485 'col_offset=0))'
486 )
487
488 def test_fix_missing_locations(self):
489 src = ast.parse('write("spam")')
490 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400491 [ast.Str('eggs')], [])))
Georg Brandl0c77a822008-06-10 16:37:50 +0000492 self.assertEqual(src, ast.fix_missing_locations(src))
493 self.assertEqual(ast.dump(src, include_attributes=True),
494 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
495 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400496 "col_offset=6)], keywords=[], "
Benjamin Peterson7a66fc22015-02-02 10:51:20 -0500497 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
Georg Brandl0c77a822008-06-10 16:37:50 +0000498 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
499 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400500 "keywords=[], lineno=1, "
INADA Naokicb41b272017-02-23 00:31:59 +0900501 "col_offset=0), lineno=1, col_offset=0)], docstring=None)"
Georg Brandl0c77a822008-06-10 16:37:50 +0000502 )
503
504 def test_increment_lineno(self):
505 src = ast.parse('1 + 1', mode='eval')
506 self.assertEqual(ast.increment_lineno(src, n=3), src)
507 self.assertEqual(ast.dump(src, include_attributes=True),
508 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
509 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
510 'col_offset=0))'
511 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000512 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000513 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000514 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
515 self.assertEqual(ast.dump(src, include_attributes=True),
516 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
517 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
518 'col_offset=0))'
519 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000520
521 def test_iter_fields(self):
522 node = ast.parse('foo()', mode='eval')
523 d = dict(ast.iter_fields(node.body))
524 self.assertEqual(d.pop('func').id, 'foo')
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400525 self.assertEqual(d, {'keywords': [], 'args': []})
Georg Brandl0c77a822008-06-10 16:37:50 +0000526
527 def test_iter_child_nodes(self):
528 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
529 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
530 iterator = ast.iter_child_nodes(node.body)
531 self.assertEqual(next(iterator).id, 'spam')
532 self.assertEqual(next(iterator).n, 23)
533 self.assertEqual(next(iterator).n, 42)
534 self.assertEqual(ast.dump(next(iterator)),
535 "keyword(arg='eggs', value=Str(s='leek'))"
536 )
537
538 def test_get_docstring(self):
539 node = ast.parse('def foo():\n """line one\n line two"""')
540 self.assertEqual(ast.get_docstring(node.body[0]),
541 'line one\nline two')
542
Yury Selivanov2f07a662015-07-23 08:54:35 +0300543 node = ast.parse('async def foo():\n """spam\n ham"""')
544 self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham')
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800545 self.assertIsNone(ast.get_docstring(ast.parse('')))
Yury Selivanov2f07a662015-07-23 08:54:35 +0300546
Georg Brandl0c77a822008-06-10 16:37:50 +0000547 def test_literal_eval(self):
548 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
549 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
550 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000551 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000552 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000553 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Raymond Hettingerbc959732010-10-08 00:47:45 +0000554 self.assertEqual(ast.literal_eval('-6'), -6)
555 self.assertEqual(ast.literal_eval('-6j+3'), 3-6j)
556 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Georg Brandl0c77a822008-06-10 16:37:50 +0000557
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000558 def test_literal_eval_issue4907(self):
559 self.assertEqual(ast.literal_eval('2j'), 2j)
560 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
561 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000562
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100563 def test_bad_integer(self):
564 # issue13436: Bad error message with invalid numeric values
565 body = [ast.ImportFrom(module='time',
566 names=[ast.alias(name='sleep')],
567 level=None,
568 lineno=None, col_offset=None)]
INADA Naokicb41b272017-02-23 00:31:59 +0900569 mod = ast.Module(body, None)
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100570 with self.assertRaises(ValueError) as cm:
571 compile(mod, 'test', 'exec')
572 self.assertIn("invalid integer value: None", str(cm.exception))
573
Berker Peksag0a5bd512016-04-29 19:50:02 +0300574 def test_level_as_none(self):
575 body = [ast.ImportFrom(module='time',
576 names=[ast.alias(name='sleep')],
577 level=None,
578 lineno=0, col_offset=0)]
INADA Naokicb41b272017-02-23 00:31:59 +0900579 mod = ast.Module(body, None)
Berker Peksag0a5bd512016-04-29 19:50:02 +0300580 code = compile(mod, 'test', 'exec')
581 ns = {}
582 exec(code, ns)
583 self.assertIn('sleep', ns)
584
Georg Brandl0c77a822008-06-10 16:37:50 +0000585
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500586class ASTValidatorTests(unittest.TestCase):
587
588 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
589 mod.lineno = mod.col_offset = 0
590 ast.fix_missing_locations(mod)
591 with self.assertRaises(exc) as cm:
592 compile(mod, "<test>", mode)
593 if msg is not None:
594 self.assertIn(msg, str(cm.exception))
595
596 def expr(self, node, msg=None, *, exc=ValueError):
INADA Naokicb41b272017-02-23 00:31:59 +0900597 mod = ast.Module([ast.Expr(node)], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500598 self.mod(mod, msg, exc=exc)
599
600 def stmt(self, stmt, msg=None):
INADA Naokicb41b272017-02-23 00:31:59 +0900601 mod = ast.Module([stmt], None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500602 self.mod(mod, msg)
603
604 def test_module(self):
605 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
606 self.mod(m, "must have Load context", "single")
607 m = ast.Expression(ast.Name("x", ast.Store()))
608 self.mod(m, "must have Load context", "eval")
609
610 def _check_arguments(self, fac, check):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700611 def arguments(args=None, vararg=None,
612 kwonlyargs=None, kwarg=None,
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500613 defaults=None, kw_defaults=None):
614 if args is None:
615 args = []
616 if kwonlyargs is None:
617 kwonlyargs = []
618 if defaults is None:
619 defaults = []
620 if kw_defaults is None:
621 kw_defaults = []
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700622 args = ast.arguments(args, vararg, kwonlyargs, kw_defaults,
623 kwarg, defaults)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500624 return fac(args)
625 args = [ast.arg("x", ast.Name("x", ast.Store()))]
626 check(arguments(args=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500627 check(arguments(kwonlyargs=args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500628 check(arguments(defaults=[ast.Num(3)]),
629 "more positional defaults than args")
630 check(arguments(kw_defaults=[ast.Num(4)]),
631 "length of kwonlyargs is not the same as kw_defaults")
632 args = [ast.arg("x", ast.Name("x", ast.Load()))]
633 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
634 "must have Load context")
635 args = [ast.arg("a", ast.Name("x", ast.Load())),
636 ast.arg("b", ast.Name("y", ast.Load()))]
637 check(arguments(kwonlyargs=args,
638 kw_defaults=[None, ast.Name("x", ast.Store())]),
639 "must have Load context")
640
641 def test_funcdef(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700642 a = ast.arguments([], None, [], [], None, [])
INADA Naokicb41b272017-02-23 00:31:59 +0900643 f = ast.FunctionDef("x", a, [], [], None, None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500644 self.stmt(f, "empty body on FunctionDef")
645 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
INADA Naokicb41b272017-02-23 00:31:59 +0900646 None, None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500647 self.stmt(f, "must have Load context")
648 f = ast.FunctionDef("x", a, [ast.Pass()], [],
INADA Naokicb41b272017-02-23 00:31:59 +0900649 ast.Name("x", ast.Store()), None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500650 self.stmt(f, "must have Load context")
651 def fac(args):
INADA Naokicb41b272017-02-23 00:31:59 +0900652 return ast.FunctionDef("x", args, [ast.Pass()], [], None, None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500653 self._check_arguments(fac, self.stmt)
654
655 def test_classdef(self):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400656 def cls(bases=None, keywords=None, body=None, decorator_list=None):
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500657 if bases is None:
658 bases = []
659 if keywords is None:
660 keywords = []
661 if body is None:
662 body = [ast.Pass()]
663 if decorator_list is None:
664 decorator_list = []
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400665 return ast.ClassDef("myclass", bases, keywords,
INADA Naokicb41b272017-02-23 00:31:59 +0900666 body, decorator_list, None)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500667 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
668 "must have Load context")
669 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
670 "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500671 self.stmt(cls(body=[]), "empty body on ClassDef")
672 self.stmt(cls(body=[None]), "None disallowed")
673 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
674 "must have Load context")
675
676 def test_delete(self):
677 self.stmt(ast.Delete([]), "empty targets on Delete")
678 self.stmt(ast.Delete([None]), "None disallowed")
679 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
680 "must have Del context")
681
682 def test_assign(self):
683 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
684 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
685 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
686 "must have Store context")
687 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
688 ast.Name("y", ast.Store())),
689 "must have Load context")
690
691 def test_augassign(self):
692 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
693 ast.Name("y", ast.Load()))
694 self.stmt(aug, "must have Store context")
695 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
696 ast.Name("y", ast.Store()))
697 self.stmt(aug, "must have Load context")
698
699 def test_for(self):
700 x = ast.Name("x", ast.Store())
701 y = ast.Name("y", ast.Load())
702 p = ast.Pass()
703 self.stmt(ast.For(x, y, [], []), "empty body on For")
704 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
705 "must have Store context")
706 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
707 "must have Load context")
708 e = ast.Expr(ast.Name("x", ast.Store()))
709 self.stmt(ast.For(x, y, [e], []), "must have Load context")
710 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
711
712 def test_while(self):
713 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
714 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
715 "must have Load context")
716 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
717 [ast.Expr(ast.Name("x", ast.Store()))]),
718 "must have Load context")
719
720 def test_if(self):
721 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
722 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
723 self.stmt(i, "must have Load context")
724 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
725 self.stmt(i, "must have Load context")
726 i = ast.If(ast.Num(3), [ast.Pass()],
727 [ast.Expr(ast.Name("x", ast.Store()))])
728 self.stmt(i, "must have Load context")
729
730 def test_with(self):
731 p = ast.Pass()
732 self.stmt(ast.With([], [p]), "empty items on With")
733 i = ast.withitem(ast.Num(3), None)
734 self.stmt(ast.With([i], []), "empty body on With")
735 i = ast.withitem(ast.Name("x", ast.Store()), None)
736 self.stmt(ast.With([i], [p]), "must have Load context")
737 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
738 self.stmt(ast.With([i], [p]), "must have Store context")
739
740 def test_raise(self):
741 r = ast.Raise(None, ast.Num(3))
742 self.stmt(r, "Raise with cause but no exception")
743 r = ast.Raise(ast.Name("x", ast.Store()), None)
744 self.stmt(r, "must have Load context")
745 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
746 self.stmt(r, "must have Load context")
747
748 def test_try(self):
749 p = ast.Pass()
750 t = ast.Try([], [], [], [p])
751 self.stmt(t, "empty body on Try")
752 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
753 self.stmt(t, "must have Load context")
754 t = ast.Try([p], [], [], [])
755 self.stmt(t, "Try has neither except handlers nor finalbody")
756 t = ast.Try([p], [], [p], [p])
757 self.stmt(t, "Try has orelse but no except handlers")
758 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
759 self.stmt(t, "empty body on ExceptHandler")
760 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
761 self.stmt(ast.Try([p], e, [], []), "must have Load context")
762 e = [ast.ExceptHandler(None, "x", [p])]
763 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
764 self.stmt(t, "must have Load context")
765 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
766 self.stmt(t, "must have Load context")
767
768 def test_assert(self):
769 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
770 "must have Load context")
771 assrt = ast.Assert(ast.Name("x", ast.Load()),
772 ast.Name("y", ast.Store()))
773 self.stmt(assrt, "must have Load context")
774
775 def test_import(self):
776 self.stmt(ast.Import([]), "empty names on Import")
777
778 def test_importfrom(self):
779 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
Serhiy Storchaka7de28402016-06-27 23:40:43 +0300780 self.stmt(imp, "Negative ImportFrom level")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500781 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
782
783 def test_global(self):
784 self.stmt(ast.Global([]), "empty names on Global")
785
786 def test_nonlocal(self):
787 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
788
789 def test_expr(self):
790 e = ast.Expr(ast.Name("x", ast.Store()))
791 self.stmt(e, "must have Load context")
792
793 def test_boolop(self):
794 b = ast.BoolOp(ast.And(), [])
795 self.expr(b, "less than 2 values")
796 b = ast.BoolOp(ast.And(), [ast.Num(3)])
797 self.expr(b, "less than 2 values")
798 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
799 self.expr(b, "None disallowed")
800 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
801 self.expr(b, "must have Load context")
802
803 def test_unaryop(self):
804 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
805 self.expr(u, "must have Load context")
806
807 def test_lambda(self):
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700808 a = ast.arguments([], None, [], [], None, [])
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500809 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
810 "must have Load context")
811 def fac(args):
812 return ast.Lambda(args, ast.Name("x", ast.Load()))
813 self._check_arguments(fac, self.expr)
814
815 def test_ifexp(self):
816 l = ast.Name("x", ast.Load())
817 s = ast.Name("y", ast.Store())
818 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500819 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500820
821 def test_dict(self):
822 d = ast.Dict([], [ast.Name("x", ast.Load())])
823 self.expr(d, "same number of keys as values")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500824 d = ast.Dict([ast.Name("x", ast.Load())], [None])
825 self.expr(d, "None disallowed")
826
827 def test_set(self):
828 self.expr(ast.Set([None]), "None disallowed")
829 s = ast.Set([ast.Name("x", ast.Store())])
830 self.expr(s, "must have Load context")
831
832 def _check_comprehension(self, fac):
833 self.expr(fac([]), "comprehension with no generators")
834 g = ast.comprehension(ast.Name("x", ast.Load()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700835 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500836 self.expr(fac([g]), "must have Store context")
837 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700838 ast.Name("x", ast.Store()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500839 self.expr(fac([g]), "must have Load context")
840 x = ast.Name("x", ast.Store())
841 y = ast.Name("y", ast.Load())
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700842 g = ast.comprehension(x, y, [None], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500843 self.expr(fac([g]), "None disallowed")
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700844 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500845 self.expr(fac([g]), "must have Load context")
846
847 def _simple_comp(self, fac):
848 g = ast.comprehension(ast.Name("x", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700849 ast.Name("x", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500850 self.expr(fac(ast.Name("x", ast.Store()), [g]),
851 "must have Load context")
852 def wrap(gens):
853 return fac(ast.Name("x", ast.Store()), gens)
854 self._check_comprehension(wrap)
855
856 def test_listcomp(self):
857 self._simple_comp(ast.ListComp)
858
859 def test_setcomp(self):
860 self._simple_comp(ast.SetComp)
861
862 def test_generatorexp(self):
863 self._simple_comp(ast.GeneratorExp)
864
865 def test_dictcomp(self):
866 g = ast.comprehension(ast.Name("y", ast.Store()),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700867 ast.Name("p", ast.Load()), [], 0)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500868 c = ast.DictComp(ast.Name("x", ast.Store()),
869 ast.Name("y", ast.Load()), [g])
870 self.expr(c, "must have Load context")
871 c = ast.DictComp(ast.Name("x", ast.Load()),
872 ast.Name("y", ast.Store()), [g])
873 self.expr(c, "must have Load context")
874 def factory(comps):
875 k = ast.Name("x", ast.Load())
876 v = ast.Name("y", ast.Load())
877 return ast.DictComp(k, v, comps)
878 self._check_comprehension(factory)
879
880 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -0500881 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
882 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500883
884 def test_compare(self):
885 left = ast.Name("x", ast.Load())
886 comp = ast.Compare(left, [ast.In()], [])
887 self.expr(comp, "no comparators")
888 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
889 self.expr(comp, "different number of comparators and operands")
890 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
891 self.expr(comp, "non-numeric", exc=TypeError)
892 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
893 self.expr(comp, "non-numeric", exc=TypeError)
894
895 def test_call(self):
896 func = ast.Name("x", ast.Load())
897 args = [ast.Name("y", ast.Load())]
898 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400899 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500900 self.expr(call, "must have Load context")
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400901 call = ast.Call(func, [None], keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500902 self.expr(call, "None disallowed")
903 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400904 call = ast.Call(func, args, bad_keywords)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500905 self.expr(call, "must have Load context")
906
907 def test_num(self):
908 class subint(int):
909 pass
910 class subfloat(float):
911 pass
912 class subcomplex(complex):
913 pass
914 for obj in "0", "hello", subint(), subfloat(), subcomplex():
915 self.expr(ast.Num(obj), "non-numeric", exc=TypeError)
916
917 def test_attribute(self):
918 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
919 self.expr(attr, "must have Load context")
920
921 def test_subscript(self):
922 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
923 ast.Load())
924 self.expr(sub, "must have Load context")
925 x = ast.Name("x", ast.Load())
926 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
927 ast.Load())
928 self.expr(sub, "must have Load context")
929 s = ast.Name("x", ast.Store())
930 for args in (s, None, None), (None, s, None), (None, None, s):
931 sl = ast.Slice(*args)
932 self.expr(ast.Subscript(x, sl, ast.Load()),
933 "must have Load context")
934 sl = ast.ExtSlice([])
935 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
936 sl = ast.ExtSlice([ast.Index(s)])
937 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
938
939 def test_starred(self):
940 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
941 ast.Store())
942 assign = ast.Assign([left], ast.Num(4))
943 self.stmt(assign, "must have Store context")
944
945 def _sequence(self, fac):
946 self.expr(fac([None], ast.Load()), "None disallowed")
947 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
948 "must have Load context")
949
950 def test_list(self):
951 self._sequence(ast.List)
952
953 def test_tuple(self):
954 self._sequence(ast.Tuple)
955
Benjamin Peterson442f2092012-12-06 17:41:04 -0500956 def test_nameconstant(self):
957 self.expr(ast.NameConstant(4), "singleton must be True, False, or None")
958
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500959 def test_stdlib_validates(self):
960 stdlib = os.path.dirname(ast.__file__)
961 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
962 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
963 for module in tests:
964 fn = os.path.join(stdlib, module)
965 with open(fn, "r", encoding="utf-8") as fp:
966 source = fp.read()
Victor Stinnerd502a072013-03-22 00:06:20 +0100967 mod = ast.parse(source, fn)
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500968 compile(mod, fn, "exec")
969
970
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100971class ConstantTests(unittest.TestCase):
972 """Tests on the ast.Constant node type."""
973
974 def compile_constant(self, value):
975 tree = ast.parse("x = 123")
976
977 node = tree.body[0].value
978 new_node = ast.Constant(value=value)
979 ast.copy_location(new_node, node)
980 tree.body[0].value = new_node
981
982 code = compile(tree, "<string>", "exec")
983
984 ns = {}
985 exec(code, ns)
986 return ns['x']
987
Victor Stinnerbe59d142016-01-27 00:39:12 +0100988 def test_validation(self):
989 with self.assertRaises(TypeError) as cm:
990 self.compile_constant([1, 2, 3])
991 self.assertEqual(str(cm.exception),
992 "got an invalid type in Constant: list")
993
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100994 def test_singletons(self):
995 for const in (None, False, True, Ellipsis, b'', frozenset()):
996 with self.subTest(const=const):
997 value = self.compile_constant(const)
998 self.assertIs(value, const)
999
1000 def test_values(self):
1001 nested_tuple = (1,)
1002 nested_frozenset = frozenset({1})
1003 for level in range(3):
1004 nested_tuple = (nested_tuple, 2)
1005 nested_frozenset = frozenset({nested_frozenset, 2})
1006 values = (123, 123.0, 123j,
1007 "unicode", b'bytes',
1008 tuple("tuple"), frozenset("frozenset"),
1009 nested_tuple, nested_frozenset)
1010 for value in values:
1011 with self.subTest(value=value):
1012 result = self.compile_constant(value)
1013 self.assertEqual(result, value)
1014
1015 def test_assign_to_constant(self):
1016 tree = ast.parse("x = 1")
1017
1018 target = tree.body[0].targets[0]
1019 new_target = ast.Constant(value=1)
1020 ast.copy_location(new_target, target)
1021 tree.body[0].targets[0] = new_target
1022
1023 with self.assertRaises(ValueError) as cm:
1024 compile(tree, "string", "exec")
1025 self.assertEqual(str(cm.exception),
1026 "expression which can't be assigned "
1027 "to in Store context")
1028
1029 def test_get_docstring(self):
1030 tree = ast.parse("'docstring'\nx = 1")
1031 self.assertEqual(ast.get_docstring(tree), 'docstring')
1032
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001033 def get_load_const(self, tree):
1034 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
1035 # instructions
1036 co = compile(tree, '<string>', 'exec')
1037 consts = []
1038 for instr in dis.get_instructions(co):
1039 if instr.opname == 'LOAD_CONST':
1040 consts.append(instr.argval)
1041 return consts
1042
1043 @support.cpython_only
1044 def test_load_const(self):
1045 consts = [None,
1046 True, False,
1047 124,
1048 2.0,
1049 3j,
1050 "unicode",
1051 b'bytes',
1052 (1, 2, 3)]
1053
Victor Stinnera2724092016-02-08 18:17:58 +01001054 code = '\n'.join(['x={!r}'.format(const) for const in consts])
1055 code += '\nx = ...'
1056 consts.extend((Ellipsis, None))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001057
1058 tree = ast.parse(code)
Victor Stinnera2724092016-02-08 18:17:58 +01001059 self.assertEqual(self.get_load_const(tree),
1060 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001061
1062 # Replace expression nodes with constants
Victor Stinnera2724092016-02-08 18:17:58 +01001063 for assign, const in zip(tree.body, consts):
1064 assert isinstance(assign, ast.Assign), ast.dump(assign)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001065 new_node = ast.Constant(value=const)
Victor Stinnera2724092016-02-08 18:17:58 +01001066 ast.copy_location(new_node, assign.value)
1067 assign.value = new_node
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001068
Victor Stinnera2724092016-02-08 18:17:58 +01001069 self.assertEqual(self.get_load_const(tree),
1070 consts)
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001071
1072 def test_literal_eval(self):
1073 tree = ast.parse("1 + 2")
1074 binop = tree.body[0].value
1075
1076 new_left = ast.Constant(value=10)
1077 ast.copy_location(new_left, binop.left)
1078 binop.left = new_left
1079
1080 new_right = ast.Constant(value=20)
1081 ast.copy_location(new_right, binop.right)
1082 binop.right = new_right
1083
1084 self.assertEqual(ast.literal_eval(binop), 30)
1085
1086
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001087def main():
1088 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001089 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001090 if sys.argv[1:] == ['-g']:
1091 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
1092 (eval_tests, "eval")):
1093 print(kind+"_results = [")
Victor Stinnerf0891962016-02-08 17:15:21 +01001094 for statement in statements:
1095 tree = ast.parse(statement, "?", kind)
1096 print("%r," % (to_tuple(tree),))
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001097 print("]")
1098 print("main()")
1099 raise SystemExit
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001100 unittest.main()
Tim Peters400cbc32006-02-28 18:44:41 +00001101
1102#### EVERYTHING BELOW IS GENERATED #####
1103exec_results = [
INADA Naokicb41b272017-02-23 00:31:59 +09001104('Module', [('Expr', (1, 0), ('NameConstant', (1, 0), None))], None),
1105('Module', [], 'module docstring'),
1106('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Pass', (1, 9))], [], None, None)], None),
1107('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [], [], None, 'function docstring')], None),
1108('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, []), [('Pass', (1, 10))], [], None, None)], None),
1109('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None)], None, [], [], None, [('Num', (1, 8), 0)]), [('Pass', (1, 12))], [], None, None)], None),
1110('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], ('arg', (1, 7), 'args', None), [], [], None, []), [('Pass', (1, 14))], [], None, None)], None),
1111('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], ('arg', (1, 8), 'kwargs', None), []), [('Pass', (1, 17))], [], None, None)], None),
1112('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', (1, 6), 'a', None), ('arg', (1, 9), 'b', None), ('arg', (1, 14), 'c', None), ('arg', (1, 22), 'd', None), ('arg', (1, 28), 'e', None)], ('arg', (1, 35), 'args', None), [('arg', (1, 41), 'f', None)], [('Num', (1, 43), 42)], ('arg', (1, 49), 'kwargs', None), [('Num', (1, 11), 1), ('NameConstant', (1, 16), None), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [], [], None, 'doc for f()')], None),
1113('Module', [('ClassDef', (1, 0), 'C', [], [], [('Pass', (1, 8))], [], None)], None),
1114('Module', [('ClassDef', (1, 0), 'C', [], [], [], [], 'docstring for class C')], None),
1115('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], [('Pass', (1, 17))], [], None)], None),
1116('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, [], [], None, []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None, None)], None),
1117('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])], None),
1118('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))], None),
1119('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))], None),
1120('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])], None),
1121('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])], None),
1122('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])], None),
1123('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])], None),
1124('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),
1125('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Str', (1, 16), 'string')], []), None)], None),
1126('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])], None),
1127('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])], None),
1128('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)], None),
1129('Module', [('Import', (1, 0), [('alias', 'sys', None)])], None),
1130('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)], None),
1131('Module', [('Global', (1, 0), ['v'])], None),
1132('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))], None),
1133('Module', [('Pass', (1, 0))], None),
1134('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Break', (1, 11))], [])], None),
1135('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Continue', (1, 11))], [])], None),
1136('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),
1137('Module', [('Expr', (1, 0), ('ListComp', (1, 1), ('Tuple', (1, 2), [('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)]))], None),
1138('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('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)]))], None),
1139('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 12), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [], 0)]))], None),
1140('Module', [('Expr', (1, 0), ('GeneratorExp', (2, 4), ('Tuple', (3, 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)]))], None),
1141('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)]))], None),
1142('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)]))], None),
1143('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)]))], None),
1144('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)]))], None),
1145('Module', [('AsyncFunctionDef', (1, 6), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (3, 1), ('Await', (3, 1), ('Call', (3, 7), ('Name', (3, 7), 'something', ('Load',)), [], [])))], [], None, 'async function')], None),
1146('Module', [('AsyncFunctionDef', (1, 6), 'f', ('arguments', [], None, [], [], None, []), [('AsyncFor', (2, 7), ('Name', (2, 11), 'e', ('Store',)), ('Name', (2, 16), 'i', ('Load',)), [('Expr', (2, 19), ('Num', (2, 19), 1))], [('Expr', (3, 7), ('Num', (3, 7), 2))])], [], None, None)], None),
1147('Module', [('AsyncFunctionDef', (1, 6), 'f', ('arguments', [], None, [], [], None, []), [('AsyncWith', (2, 7), [('withitem', ('Name', (2, 12), 'a', ('Load',)), ('Name', (2, 17), 'b', ('Store',)))], [('Expr', (2, 20), ('Num', (2, 20), 1))])], [], None, None)], None),
1148('Module', [('Expr', (1, 0), ('Dict', (1, 0), [None, ('Num', (1, 10), 2)], [('Dict', (1, 3), [('Num', (1, 4), 1)], [('Num', (1, 6), 2)]), ('Num', (1, 12), 3)]))], None),
1149('Module', [('Expr', (1, 0), ('Set', (1, 0), [('Starred', (1, 1), ('Set', (1, 2), [('Num', (1, 3), 1), ('Num', (1, 6), 2)]), ('Load',)), ('Num', (1, 10), 3)]))], None),
1150('Module', [('AsyncFunctionDef', (1, 6), 'f', ('arguments', [], None, [], [], None, []), [('Expr', (2, 1), ('ListComp', (2, 2), ('Name', (2, 2), 'i', ('Load',)), [('comprehension', ('Name', (2, 14), 'b', ('Store',)), ('Name', (2, 19), 'c', ('Load',)), [], 1)]))], [], None, None)], None),
Tim Peters400cbc32006-02-28 18:44:41 +00001151]
1152single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001153('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +00001154]
1155eval_results = [
Benjamin Peterson442f2092012-12-06 17:41:04 -05001156('Expression', ('NameConstant', (1, 0), None)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001157('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
1158('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
1159('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001160('Expression', ('Lambda', (1, 0), ('arguments', [], None, [], [], None, []), ('NameConstant', (1, 7), None))),
Benjamin Peterson58b53952015-09-25 22:44:43 -07001161('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001162('Expression', ('Dict', (1, 0), [], [])),
Benjamin Peterson58b53952015-09-25 22:44:43 -07001163('Expression', ('Set', (1, 0), [('NameConstant', (1, 1), None)])),
1164('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])),
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07001165('Expression', ('ListComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
1166('Expression', ('GeneratorExp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))], 0)])),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001167('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001168('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Num', (1, 2), 1), ('Num', (1, 4), 2), ('Starred', (1, 10), ('Name', (1, 11), 'd', ('Load',)), ('Load',))], [('keyword', 'c', ('Num', (1, 8), 3)), ('keyword', None, ('Name', (1, 15), 'e', ('Load',)))])),
Neal Norwitzc1505362006-12-28 06:47:50 +00001169('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001170('Expression', ('Str', (1, 0), 'string')),
Benjamin Peterson7a66fc22015-02-02 10:51:20 -05001171('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
1172('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 +00001173('Expression', ('Name', (1, 0), 'v', ('Load',))),
1174('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001175('Expression', ('List', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +00001176('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -05001177('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
1178('Expression', ('Tuple', (1, 0), [], ('Load',))),
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001179('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', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [])),
Tim Peters400cbc32006-02-28 18:44:41 +00001180]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001181main()