Debian Codegraph @

Lib/test/test_ast/test_ast.py

raw
1 import ast
2 import builtins
3 import copy
4 import dis
5 import enum
6 import os
7 import re
8 import sys
9 import textwrap
10 import types
11 import unittest
12 import warnings
13 import weakref
14 from functools import partial
15 from textwrap import dedent
16
17 try:
18 import _testinternalcapi
19 except ImportError:
20 _testinternalcapi = None
21
22 from test import support
23 from test.support.import_helper import import_fresh_module
24 from test.support import os_helper, script_helper
25 from test.support.ast_helper import ASTTestMixin
26 from test.test_ast.utils import to_tuple
27 from test.test_ast.snippets import (
28 eval_tests, eval_results, exec_tests, exec_results, single_tests, single_results
29 )
30
31
32 class AST_Tests(unittest.TestCase):
33 maxDiff = None
34
35 def _is_ast_node(self, name, node):
36 if not isinstance(node, type):
37 return False
38 if "ast" not in node.__module__:
39 return False
40 return name != "AST" and name[0].isupper()
41
42 def _assertTrueorder(self, ast_node, parent_pos):
43 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
44 return
45 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
46 node_pos = (ast_node.lineno, ast_node.col_offset)
47 self.assertGreaterEqual(node_pos, parent_pos)
48 parent_pos = (ast_node.lineno, ast_node.col_offset)
49 for name in ast_node._fields:
50 value = getattr(ast_node, name)
51 if isinstance(value, list):
52 first_pos = parent_pos
53 if value and name == "decorator_list":
54 first_pos = (value[0].lineno, value[0].col_offset)
55 for child in value:
56 self._assertTrueorder(child, first_pos)
57 elif value is not None:
58 self._assertTrueorder(value, parent_pos)
59 self.assertEqual(ast_node._fields, ast_node.__match_args__)
60
61 def test_AST_objects(self):
62 x = ast.AST()
63 self.assertEqual(x._fields, ())
64 x.foobar = 42
65 self.assertEqual(x.foobar, 42)
66 self.assertEqual(x.__dict__["foobar"], 42)
67
68 with self.assertRaises(AttributeError):
69 x.vararg
70
71 with self.assertRaises(TypeError):
72 # "ast.AST constructor takes 0 positional arguments"
73 ast.AST(2)
74
75 def test_AST_fields_NULL_check(self):
76 # See: https://github.com/python/cpython/issues/126105
77 old_value = ast.AST._fields
78
79 def cleanup():
80 ast.AST._fields = old_value
81 self.addCleanup(cleanup)
82
83 del ast.AST._fields
84
85 msg = "type object 'ast.AST' has no attribute '_fields'"
86 # Both examples used to crash:
87 with self.assertRaisesRegex(AttributeError, msg):
88 ast.AST(arg1=123)
89 with self.assertRaisesRegex(AttributeError, msg):
90 ast.AST()
91
92 def test_AST_garbage_collection(self):
93 class X:
94 pass
95
96 a = ast.AST()
97 a.x = X()
98 a.x.a = a
99 ref = weakref.ref(a.x)
100 del a
101 support.gc_collect()
102 self.assertIsNone(ref())
103
104 def test_snippets(self):
105 for input, output, kind in (
106 (exec_tests, exec_results, "exec"),
107 (single_tests, single_results, "single"),
108 (eval_tests, eval_results, "eval"),
109 ):
110 for i, o in zip(input, output):
111 with self.subTest(action="parsing", input=i):
112 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
113 self.assertEqual(to_tuple(ast_tree), o)
114 self._assertTrueorder(ast_tree, (0, 0))
115 with self.subTest(action="compiling", input=i, kind=kind):
116 compile(ast_tree, "?", kind)
117
118 def test_ast_validation(self):
119 # compile() is the only function that calls PyAST_Validate
120 snippets_to_validate = exec_tests + single_tests + eval_tests
121 for snippet in snippets_to_validate:
122 tree = ast.parse(snippet)
123 compile(tree, "<string>", "exec")
124
125 def test_optimization_levels__debug__(self):
126 cases = [(-1, "__debug__"), (0, "__debug__"), (1, False), (2, False)]
127 for optval, expected in cases:
128 with self.subTest(optval=optval, expected=expected):
129 res1 = ast.parse("__debug__", optimize=optval)
130 res2 = ast.parse(ast.parse("__debug__"), optimize=optval)
131 for res in [res1, res2]:
132 self.assertIsInstance(res.body[0], ast.Expr)
133 if isinstance(expected, bool):
134 self.assertIsInstance(res.body[0].value, ast.Constant)
135 self.assertEqual(res.body[0].value.value, expected)
136 else:
137 self.assertIsInstance(res.body[0].value, ast.Name)
138 self.assertEqual(res.body[0].value.id, expected)
139
140 def test_optimization_levels_const_folding(self):
141 folded = ("Expr", (1, 0, 1, 5), ("Constant", (1, 0, 1, 5), 3, None))
142 not_folded = (
143 "Expr",
144 (1, 0, 1, 5),
145 (
146 "BinOp",
147 (1, 0, 1, 5),
148 ("Constant", (1, 0, 1, 1), 1, None),
149 ("Add",),
150 ("Constant", (1, 4, 1, 5), 2, None),
151 ),
152 )
153
154 cases = [(-1, not_folded), (0, not_folded), (1, folded), (2, folded)]
155 for optval, expected in cases:
156 with self.subTest(optval=optval):
157 tree1 = ast.parse("1 + 2", optimize=optval)
158 tree2 = ast.parse(ast.parse("1 + 2"), optimize=optval)
159 for tree in [tree1, tree2]:
160 res = to_tuple(tree.body[0])
161 self.assertEqual(res, expected)
162
163 def test_invalid_position_information(self):
164 invalid_linenos = [(10, 1), (-10, -11), (10, -11), (-5, -2), (-5, 1)]
165
166 for lineno, end_lineno in invalid_linenos:
167 with self.subTest(f"Check invalid linenos {lineno}:{end_lineno}"):
168 snippet = "a = 1"
169 tree = ast.parse(snippet)
170 tree.body[0].lineno = lineno
171 tree.body[0].end_lineno = end_lineno
172 with self.assertRaises(ValueError):
173 compile(tree, "<string>", "exec")
174
175 invalid_col_offsets = [(10, 1), (-10, -11), (10, -11), (-5, -2), (-5, 1)]
176 for col_offset, end_col_offset in invalid_col_offsets:
177 with self.subTest(
178 f"Check invalid col_offset {col_offset}:{end_col_offset}"
179 ):
180 snippet = "a = 1"
181 tree = ast.parse(snippet)
182 tree.body[0].col_offset = col_offset
183 tree.body[0].end_col_offset = end_col_offset
184 with self.assertRaises(ValueError):
185 compile(tree, "<string>", "exec")
186
187 def test_compilation_of_ast_nodes_with_default_end_position_values(self):
188 tree = ast.Module(
189 body=[
190 ast.Import(
191 names=[ast.alias(name="builtins", lineno=1, col_offset=0)],
192 lineno=1,
193 col_offset=0,
194 ),
195 ast.Import(
196 names=[ast.alias(name="traceback", lineno=0, col_offset=0)],
197 lineno=0,
198 col_offset=1,
199 ),
200 ],
201 type_ignores=[],
202 )
203
204 # Check that compilation doesn't crash. Note: this may crash explicitly only on debug mode.
205 compile(tree, "<string>", "exec")
206
207 def test_negative_locations_for_compile(self):
208 # See https://github.com/python/cpython/issues/130775
209 alias = ast.alias(name='traceback', lineno=0, col_offset=0)
210 for attrs in (
211 {'lineno': -2, 'col_offset': 0},
212 {'lineno': 0, 'col_offset': -2},
213 {'lineno': 0, 'col_offset': -2, 'end_col_offset': -2},
214 {'lineno': -2, 'end_lineno': -2, 'col_offset': 0},
215 ):
216 with self.subTest(attrs=attrs):
217 tree = ast.Module(body=[
218 ast.Import(names=[alias], **attrs)
219 ], type_ignores=[])
220
221 # It used to crash on this step:
222 compile(tree, "<string>", "exec")
223
224 # This also must not crash:
225 ast.parse(tree, optimize=2)
226
227 def test_slice(self):
228 slc = ast.parse("x[::]").body[0].value.slice
229 self.assertIsNone(slc.upper)
230 self.assertIsNone(slc.lower)
231 self.assertIsNone(slc.step)
232
233 def test_from_import(self):
234 im = ast.parse("from . import y").body[0]
235 self.assertIsNone(im.module)
236
237 def test_non_interned_future_from_ast(self):
238 mod = ast.parse("from __future__ import division")
239 self.assertIsInstance(mod.body[0], ast.ImportFrom)
240 mod.body[0].module = " __future__ ".strip()
241 compile(mod, "<test>", "exec")
242
243 def test_alias(self):
244 im = ast.parse("from bar import y").body[0]
245 self.assertEqual(len(im.names), 1)
246 alias = im.names[0]
247 self.assertEqual(alias.name, "y")
248 self.assertIsNone(alias.asname)
249 self.assertEqual(alias.lineno, 1)
250 self.assertEqual(alias.end_lineno, 1)
251 self.assertEqual(alias.col_offset, 16)
252 self.assertEqual(alias.end_col_offset, 17)
253
254 im = ast.parse("from bar import *").body[0]
255 alias = im.names[0]
256 self.assertEqual(alias.name, "*")
257 self.assertIsNone(alias.asname)
258 self.assertEqual(alias.lineno, 1)
259 self.assertEqual(alias.end_lineno, 1)
260 self.assertEqual(alias.col_offset, 16)
261 self.assertEqual(alias.end_col_offset, 17)
262
263 im = ast.parse("from bar import y as z").body[0]
264 alias = im.names[0]
265 self.assertEqual(alias.name, "y")
266 self.assertEqual(alias.asname, "z")
267 self.assertEqual(alias.lineno, 1)
268 self.assertEqual(alias.end_lineno, 1)
269 self.assertEqual(alias.col_offset, 16)
270 self.assertEqual(alias.end_col_offset, 22)
271
272 im = ast.parse("import bar as foo").body[0]
273 alias = im.names[0]
274 self.assertEqual(alias.name, "bar")
275 self.assertEqual(alias.asname, "foo")
276 self.assertEqual(alias.lineno, 1)
277 self.assertEqual(alias.end_lineno, 1)
278 self.assertEqual(alias.col_offset, 7)
279 self.assertEqual(alias.end_col_offset, 17)
280
281 def test_base_classes(self):
282 self.assertTrue(issubclass(ast.For, ast.stmt))
283 self.assertTrue(issubclass(ast.Name, ast.expr))
284 self.assertTrue(issubclass(ast.stmt, ast.AST))
285 self.assertTrue(issubclass(ast.expr, ast.AST))
286 self.assertTrue(issubclass(ast.comprehension, ast.AST))
287 self.assertTrue(issubclass(ast.Gt, ast.AST))
288
289 def test_import_deprecated(self):
290 ast = import_fresh_module("ast")
291 depr_regex = (
292 r"ast\.{} is deprecated and will be removed in Python 3.14; "
293 r"use ast\.Constant instead"
294 )
295 for name in "Num", "Str", "Bytes", "NameConstant", "Ellipsis":
296 with self.assertWarnsRegex(DeprecationWarning, depr_regex.format(name)):
297 getattr(ast, name)
298
299 def test_field_attr_existence_deprecated(self):
300 with warnings.catch_warnings():
301 warnings.filterwarnings("ignore", "", DeprecationWarning)
302 from ast import Num, Str, Bytes, NameConstant, Ellipsis
303
304 for name in ("Num", "Str", "Bytes", "NameConstant", "Ellipsis"):
305 item = getattr(ast, name)
306 if self._is_ast_node(name, item):
307 with self.subTest(item):
308 with self.assertWarns(DeprecationWarning):
309 x = item()
310 if isinstance(x, ast.AST):
311 self.assertIs(type(x._fields), tuple)
312
313 def test_field_attr_existence(self):
314 for name, item in ast.__dict__.items():
315 # These emit DeprecationWarnings
316 if name in {"Num", "Str", "Bytes", "NameConstant", "Ellipsis"}:
317 continue
318 # constructor has a different signature
319 if name == "Index":
320 continue
321 if self._is_ast_node(name, item):
322 x = self._construct_ast_class(item)
323 if isinstance(x, ast.AST):
324 self.assertIs(type(x._fields), tuple)
325
326 def _construct_ast_class(self, cls):
327 kwargs = {}
328 for name, typ in cls.__annotations__.items():
329 if typ is str:
330 kwargs[name] = "capybara"
331 elif typ is int:
332 kwargs[name] = 42
333 elif typ is object:
334 kwargs[name] = b"capybara"
335 elif isinstance(typ, type) and issubclass(typ, ast.AST):
336 kwargs[name] = self._construct_ast_class(typ)
337 return cls(**kwargs)
338
339 def test_arguments(self):
340 x = ast.arguments()
341 self.assertEqual(
342 x._fields,
343 (
344 "posonlyargs",
345 "args",
346 "vararg",
347 "kwonlyargs",
348 "kw_defaults",
349 "kwarg",
350 "defaults",
351 ),
352 )
353 self.assertEqual(
354 x.__annotations__,
355 {
356 "posonlyargs": list[ast.arg],
357 "args": list[ast.arg],
358 "vararg": ast.arg | None,
359 "kwonlyargs": list[ast.arg],
360 "kw_defaults": list[ast.expr],
361 "kwarg": ast.arg | None,
362 "defaults": list[ast.expr],
363 },
364 )
365
366 self.assertEqual(x.args, [])
367 self.assertIsNone(x.vararg)
368
369 x = ast.arguments(*range(1, 8))
370 self.assertEqual(x.args, 2)
371 self.assertEqual(x.vararg, 3)
372
373 def test_field_attr_writable_deprecated(self):
374 with warnings.catch_warnings():
375 warnings.filterwarnings("ignore", "", DeprecationWarning)
376 x = ast.Num()
377 # We can assign to _fields
378 x._fields = 666
379 self.assertEqual(x._fields, 666)
380
381 def test_field_attr_writable(self):
382 x = ast.Constant(1)
383 # We can assign to _fields
384 x._fields = 666
385 self.assertEqual(x._fields, 666)
386
387 def test_classattrs_deprecated(self):
388 with warnings.catch_warnings():
389 warnings.filterwarnings("ignore", "", DeprecationWarning)
390 from ast import Num, Str, Bytes, NameConstant, Ellipsis
391
392 with warnings.catch_warnings(record=True) as wlog:
393 warnings.filterwarnings("always", "", DeprecationWarning)
394 x = ast.Num()
395 self.assertEqual(x._fields, ("value", "kind"))
396
397 with self.assertRaises(AttributeError):
398 x.value
399
400 with self.assertRaises(AttributeError):
401 x.n
402
403 x = ast.Num(42)
404 self.assertEqual(x.value, 42)
405 self.assertEqual(x.n, 42)
406
407 with self.assertRaises(AttributeError):
408 x.lineno
409
410 with self.assertRaises(AttributeError):
411 x.foobar
412
413 x = ast.Num(lineno=2)
414 self.assertEqual(x.lineno, 2)
415
416 x = ast.Num(42, lineno=0)
417 self.assertEqual(x.lineno, 0)
418 self.assertEqual(x._fields, ("value", "kind"))
419 self.assertEqual(x.value, 42)
420 self.assertEqual(x.n, 42)
421
422 self.assertRaises(TypeError, ast.Num, 1, None, 2)
423 self.assertRaises(TypeError, ast.Num, 1, None, 2, lineno=0)
424
425 # Arbitrary keyword arguments are supported
426 self.assertEqual(ast.Num(1, foo="bar").foo, "bar")
427
428 with self.assertRaisesRegex(
429 TypeError, "Num got multiple values for argument 'n'"
430 ):
431 ast.Num(1, n=2)
432
433 self.assertEqual(ast.Num(42).n, 42)
434 self.assertEqual(ast.Num(4.25).n, 4.25)
435 self.assertEqual(ast.Num(4.25j).n, 4.25j)
436 self.assertEqual(ast.Str("42").s, "42")
437 self.assertEqual(ast.Bytes(b"42").s, b"42")
438 self.assertIs(ast.NameConstant(True).value, True)
439 self.assertIs(ast.NameConstant(False).value, False)
440 self.assertIs(ast.NameConstant(None).value, None)
441
442 self.assertEqual(
443 [str(w.message) for w in wlog],
444 [
445 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
446 "Constant.__init__ missing 1 required positional argument: 'value'. This will become "
447 "an error in Python 3.15.",
448 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
449 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
450 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
451 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
452 "Constant.__init__ missing 1 required positional argument: 'value'. This will become "
453 "an error in Python 3.15.",
454 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
455 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
456 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
457 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
458 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
459 "Constant.__init__ got an unexpected keyword argument 'foo'. Support for "
460 "arbitrary keyword arguments is deprecated and will be removed in Python "
461 "3.15.",
462 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
463 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
464 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
465 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
466 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
467 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
468 "ast.Str is deprecated and will be removed in Python 3.14; use ast.Constant instead",
469 "Attribute s is deprecated and will be removed in Python 3.14; use value instead",
470 "ast.Bytes is deprecated and will be removed in Python 3.14; use ast.Constant instead",
471 "Attribute s is deprecated and will be removed in Python 3.14; use value instead",
472 "ast.NameConstant is deprecated and will be removed in Python 3.14; use ast.Constant instead",
473 "ast.NameConstant is deprecated and will be removed in Python 3.14; use ast.Constant instead",
474 "ast.NameConstant is deprecated and will be removed in Python 3.14; use ast.Constant instead",
475 ],
476 )
477
478 def test_classattrs(self):
479 with self.assertWarns(DeprecationWarning):
480 x = ast.Constant()
481 self.assertEqual(x._fields, ("value", "kind"))
482
483 with self.assertRaises(AttributeError):
484 x.value
485
486 x = ast.Constant(42)
487 self.assertEqual(x.value, 42)
488
489 with self.assertRaises(AttributeError):
490 x.lineno
491
492 with self.assertRaises(AttributeError):
493 x.foobar
494
495 x = ast.Constant(lineno=2, value=3)
496 self.assertEqual(x.lineno, 2)
497
498 x = ast.Constant(42, lineno=0)
499 self.assertEqual(x.lineno, 0)
500 self.assertEqual(x._fields, ("value", "kind"))
501 self.assertEqual(x.value, 42)
502
503 self.assertRaises(TypeError, ast.Constant, 1, None, 2)
504 self.assertRaises(TypeError, ast.Constant, 1, None, 2, lineno=0)
505
506 # Arbitrary keyword arguments are supported (but deprecated)
507 with self.assertWarns(DeprecationWarning):
508 self.assertEqual(ast.Constant(1, foo="bar").foo, "bar")
509
510 with self.assertRaisesRegex(
511 TypeError, "Constant got multiple values for argument 'value'"
512 ):
513 ast.Constant(1, value=2)
514
515 self.assertEqual(ast.Constant(42).value, 42)
516 self.assertEqual(ast.Constant(4.25).value, 4.25)
517 self.assertEqual(ast.Constant(4.25j).value, 4.25j)
518 self.assertEqual(ast.Constant("42").value, "42")
519 self.assertEqual(ast.Constant(b"42").value, b"42")
520 self.assertIs(ast.Constant(True).value, True)
521 self.assertIs(ast.Constant(False).value, False)
522 self.assertIs(ast.Constant(None).value, None)
523 self.assertIs(ast.Constant(...).value, ...)
524
525 def test_realtype(self):
526 with warnings.catch_warnings():
527 warnings.filterwarnings("ignore", "", DeprecationWarning)
528 from ast import Num, Str, Bytes, NameConstant, Ellipsis
529
530 with warnings.catch_warnings(record=True) as wlog:
531 warnings.filterwarnings("always", "", DeprecationWarning)
532 self.assertIs(type(ast.Num(42)), ast.Constant)
533 self.assertIs(type(ast.Num(4.25)), ast.Constant)
534 self.assertIs(type(ast.Num(4.25j)), ast.Constant)
535 self.assertIs(type(ast.Str("42")), ast.Constant)
536 self.assertIs(type(ast.Bytes(b"42")), ast.Constant)
537 self.assertIs(type(ast.NameConstant(True)), ast.Constant)
538 self.assertIs(type(ast.NameConstant(False)), ast.Constant)
539 self.assertIs(type(ast.NameConstant(None)), ast.Constant)
540 self.assertIs(type(ast.Ellipsis()), ast.Constant)
541
542 self.assertEqual(
543 [str(w.message) for w in wlog],
544 [
545 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
546 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
547 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
548 "ast.Str is deprecated and will be removed in Python 3.14; use ast.Constant instead",
549 "ast.Bytes is deprecated and will be removed in Python 3.14; use ast.Constant instead",
550 "ast.NameConstant is deprecated and will be removed in Python 3.14; use ast.Constant instead",
551 "ast.NameConstant is deprecated and will be removed in Python 3.14; use ast.Constant instead",
552 "ast.NameConstant is deprecated and will be removed in Python 3.14; use ast.Constant instead",
553 "ast.Ellipsis is deprecated and will be removed in Python 3.14; use ast.Constant instead",
554 ],
555 )
556
557 def test_isinstance(self):
558 from ast import Constant
559
560 with warnings.catch_warnings():
561 warnings.filterwarnings("ignore", "", DeprecationWarning)
562 from ast import Num, Str, Bytes, NameConstant, Ellipsis
563
564 cls_depr_msg = (
565 "ast.{} is deprecated and will be removed in Python 3.14; "
566 "use ast.Constant instead"
567 )
568
569 assertNumDeprecated = partial(
570 self.assertWarnsRegex, DeprecationWarning, cls_depr_msg.format("Num")
571 )
572 assertStrDeprecated = partial(
573 self.assertWarnsRegex, DeprecationWarning, cls_depr_msg.format("Str")
574 )
575 assertBytesDeprecated = partial(
576 self.assertWarnsRegex, DeprecationWarning, cls_depr_msg.format("Bytes")
577 )
578 assertNameConstantDeprecated = partial(
579 self.assertWarnsRegex,
580 DeprecationWarning,
581 cls_depr_msg.format("NameConstant"),
582 )
583 assertEllipsisDeprecated = partial(
584 self.assertWarnsRegex, DeprecationWarning, cls_depr_msg.format("Ellipsis")
585 )
586
587 for arg in 42, 4.2, 4.2j:
588 with self.subTest(arg=arg):
589 with assertNumDeprecated():
590 n = Num(arg)
591 with assertNumDeprecated():
592 self.assertIsInstance(n, Num)
593
594 with assertStrDeprecated():
595 s = Str("42")
596 with assertStrDeprecated():
597 self.assertIsInstance(s, Str)
598
599 with assertBytesDeprecated():
600 b = Bytes(b"42")
601 with assertBytesDeprecated():
602 self.assertIsInstance(b, Bytes)
603
604 for arg in True, False, None:
605 with self.subTest(arg=arg):
606 with assertNameConstantDeprecated():
607 n = NameConstant(arg)
608 with assertNameConstantDeprecated():
609 self.assertIsInstance(n, NameConstant)
610
611 with assertEllipsisDeprecated():
612 e = Ellipsis()
613 with assertEllipsisDeprecated():
614 self.assertIsInstance(e, Ellipsis)
615
616 for arg in 42, 4.2, 4.2j:
617 with self.subTest(arg=arg):
618 with assertNumDeprecated():
619 self.assertIsInstance(Constant(arg), Num)
620
621 with assertStrDeprecated():
622 self.assertIsInstance(Constant("42"), Str)
623
624 with assertBytesDeprecated():
625 self.assertIsInstance(Constant(b"42"), Bytes)
626
627 for arg in True, False, None:
628 with self.subTest(arg=arg):
629 with assertNameConstantDeprecated():
630 self.assertIsInstance(Constant(arg), NameConstant)
631
632 with assertEllipsisDeprecated():
633 self.assertIsInstance(Constant(...), Ellipsis)
634
635 with assertStrDeprecated():
636 s = Str("42")
637 assertNumDeprecated(self.assertNotIsInstance, s, Num)
638 assertBytesDeprecated(self.assertNotIsInstance, s, Bytes)
639
640 with assertNumDeprecated():
641 n = Num(42)
642 assertStrDeprecated(self.assertNotIsInstance, n, Str)
643 assertNameConstantDeprecated(self.assertNotIsInstance, n, NameConstant)
644 assertEllipsisDeprecated(self.assertNotIsInstance, n, Ellipsis)
645
646 with assertNameConstantDeprecated():
647 n = NameConstant(True)
648 with assertNumDeprecated():
649 self.assertNotIsInstance(n, Num)
650
651 with assertNameConstantDeprecated():
652 n = NameConstant(False)
653 with assertNumDeprecated():
654 self.assertNotIsInstance(n, Num)
655
656 for arg in "42", True, False:
657 with self.subTest(arg=arg):
658 with assertNumDeprecated():
659 self.assertNotIsInstance(Constant(arg), Num)
660
661 assertStrDeprecated(self.assertNotIsInstance, Constant(42), Str)
662 assertBytesDeprecated(self.assertNotIsInstance, Constant("42"), Bytes)
663 assertNameConstantDeprecated(
664 self.assertNotIsInstance, Constant(42), NameConstant
665 )
666 assertEllipsisDeprecated(self.assertNotIsInstance, Constant(42), Ellipsis)
667 assertNumDeprecated(self.assertNotIsInstance, Constant(None), Num)
668 assertStrDeprecated(self.assertNotIsInstance, Constant(None), Str)
669 assertBytesDeprecated(self.assertNotIsInstance, Constant(None), Bytes)
670 assertNameConstantDeprecated(
671 self.assertNotIsInstance, Constant(1), NameConstant
672 )
673 assertEllipsisDeprecated(self.assertNotIsInstance, Constant(None), Ellipsis)
674
675 class S(str):
676 pass
677
678 with assertStrDeprecated():
679 self.assertIsInstance(Constant(S("42")), Str)
680 with assertNumDeprecated():
681 self.assertNotIsInstance(Constant(S("42")), Num)
682
683 def test_constant_subclasses_deprecated(self):
684 with warnings.catch_warnings():
685 warnings.filterwarnings("ignore", "", DeprecationWarning)
686 from ast import Num
687
688 with warnings.catch_warnings(record=True) as wlog:
689 warnings.filterwarnings("always", "", DeprecationWarning)
690
691 class N(ast.Num):
692 def __init__(self, *args, **kwargs):
693 super().__init__(*args, **kwargs)
694 self.z = "spam"
695
696 class N2(ast.Num):
697 pass
698
699 n = N(42)
700 self.assertEqual(n.n, 42)
701 self.assertEqual(n.z, "spam")
702 self.assertIs(type(n), N)
703 self.assertIsInstance(n, N)
704 self.assertIsInstance(n, ast.Num)
705 self.assertNotIsInstance(n, N2)
706 self.assertNotIsInstance(ast.Num(42), N)
707 n = N(n=42)
708 self.assertEqual(n.n, 42)
709 self.assertIs(type(n), N)
710
711 self.assertEqual(
712 [str(w.message) for w in wlog],
713 [
714 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
715 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
716 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
717 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
718 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
719 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
720 ],
721 )
722
723 def test_constant_subclasses(self):
724 class N(ast.Constant):
725 def __init__(self, *args, **kwargs):
726 super().__init__(*args, **kwargs)
727 self.z = "spam"
728
729 class N2(ast.Constant):
730 pass
731
732 n = N(42)
733 self.assertEqual(n.value, 42)
734 self.assertEqual(n.z, "spam")
735 self.assertEqual(type(n), N)
736 self.assertTrue(isinstance(n, N))
737 self.assertTrue(isinstance(n, ast.Constant))
738 self.assertFalse(isinstance(n, N2))
739 self.assertFalse(isinstance(ast.Constant(42), N))
740 n = N(value=42)
741 self.assertEqual(n.value, 42)
742 self.assertEqual(type(n), N)
743
744 def test_module(self):
745 body = [ast.Constant(42)]
746 x = ast.Module(body, [])
747 self.assertEqual(x.body, body)
748
749 def test_nodeclasses(self):
750 # Zero arguments constructor explicitly allowed (but deprecated)
751 with self.assertWarns(DeprecationWarning):
752 x = ast.BinOp()
753 self.assertEqual(x._fields, ("left", "op", "right"))
754
755 # Random attribute allowed too
756 x.foobarbaz = 5
757 self.assertEqual(x.foobarbaz, 5)
758
759 n1 = ast.Constant(1)
760 n3 = ast.Constant(3)
761 addop = ast.Add()
762 x = ast.BinOp(n1, addop, n3)
763 self.assertEqual(x.left, n1)
764 self.assertEqual(x.op, addop)
765 self.assertEqual(x.right, n3)
766
767 x = ast.BinOp(1, 2, 3)
768 self.assertEqual(x.left, 1)
769 self.assertEqual(x.op, 2)
770 self.assertEqual(x.right, 3)
771
772 x = ast.BinOp(1, 2, 3, lineno=0)
773 self.assertEqual(x.left, 1)
774 self.assertEqual(x.op, 2)
775 self.assertEqual(x.right, 3)
776 self.assertEqual(x.lineno, 0)
777
778 # node raises exception when given too many arguments
779 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
780 # node raises exception when given too many arguments
781 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
782
783 # can set attributes through kwargs too
784 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
785 self.assertEqual(x.left, 1)
786 self.assertEqual(x.op, 2)
787 self.assertEqual(x.right, 3)
788 self.assertEqual(x.lineno, 0)
789
790 # Random kwargs also allowed (but deprecated)
791 with self.assertWarns(DeprecationWarning):
792 x = ast.BinOp(1, 2, 3, foobarbaz=42)
793 self.assertEqual(x.foobarbaz, 42)
794
795 def test_no_fields(self):
796 # this used to fail because Sub._fields was None
797 x = ast.Sub()
798 self.assertEqual(x._fields, ())
799
800 def test_invalid_sum(self):
801 pos = dict(lineno=2, col_offset=3)
802 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], [])
803 with self.assertRaises(TypeError) as cm:
804 compile(m, "<test>", "exec")
805 self.assertIn("but got <ast.expr", str(cm.exception))
806
807 def test_invalid_identifier(self):
808 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))], [])
809 ast.fix_missing_locations(m)
810 with self.assertRaises(TypeError) as cm:
811 compile(m, "<test>", "exec")
812 self.assertIn("identifier must be of type str", str(cm.exception))
813
814 def test_invalid_constant(self):
815 for invalid_constant in int, (1, 2, int), frozenset((1, 2, int)):
816 e = ast.Expression(body=ast.Constant(invalid_constant))
817 ast.fix_missing_locations(e)
818 with self.assertRaisesRegex(TypeError, "invalid type in Constant: type"):
819 compile(e, "<test>", "eval")
820
821 def test_empty_yield_from(self):
822 # Issue 16546: yield from value is not optional.
823 empty_yield_from = ast.parse("def f():\n yield from g()")
824 empty_yield_from.body[0].body[0].value.value = None
825 with self.assertRaises(ValueError) as cm:
826 compile(empty_yield_from, "<test>", "exec")
827 self.assertIn("field 'value' is required", str(cm.exception))
828
829 @support.cpython_only
830 def test_issue31592(self):
831 # There shouldn't be an assertion failure in case of a bad
832 # unicodedata.normalize().
833 import unicodedata
834
835 def bad_normalize(*args):
836 return None
837
838 with support.swap_attr(unicodedata, "normalize", bad_normalize):
839 self.assertRaises(TypeError, ast.parse, "\u03d5")
840
841 def test_issue18374_binop_col_offset(self):
842 tree = ast.parse("4+5+6+7")
843 parent_binop = tree.body[0].value
844 child_binop = parent_binop.left
845 grandchild_binop = child_binop.left
846 self.assertEqual(parent_binop.col_offset, 0)
847 self.assertEqual(parent_binop.end_col_offset, 7)
848 self.assertEqual(child_binop.col_offset, 0)
849 self.assertEqual(child_binop.end_col_offset, 5)
850 self.assertEqual(grandchild_binop.col_offset, 0)
851 self.assertEqual(grandchild_binop.end_col_offset, 3)
852
853 tree = ast.parse("4+5-\\\n 6-7")
854 parent_binop = tree.body[0].value
855 child_binop = parent_binop.left
856 grandchild_binop = child_binop.left
857 self.assertEqual(parent_binop.col_offset, 0)
858 self.assertEqual(parent_binop.lineno, 1)
859 self.assertEqual(parent_binop.end_col_offset, 4)
860 self.assertEqual(parent_binop.end_lineno, 2)
861
862 self.assertEqual(child_binop.col_offset, 0)
863 self.assertEqual(child_binop.lineno, 1)
864 self.assertEqual(child_binop.end_col_offset, 2)
865 self.assertEqual(child_binop.end_lineno, 2)
866
867 self.assertEqual(grandchild_binop.col_offset, 0)
868 self.assertEqual(grandchild_binop.lineno, 1)
869 self.assertEqual(grandchild_binop.end_col_offset, 3)
870 self.assertEqual(grandchild_binop.end_lineno, 1)
871
872 def test_issue39579_dotted_name_end_col_offset(self):
873 tree = ast.parse("@a.b.c\ndef f(): pass")
874 attr_b = tree.body[0].decorator_list[0].value
875 self.assertEqual(attr_b.end_col_offset, 4)
876
877 def test_ast_asdl_signature(self):
878 self.assertEqual(
879 ast.withitem.__doc__, "withitem(expr context_expr, expr? optional_vars)"
880 )
881 self.assertEqual(ast.GtE.__doc__, "GtE")
882 self.assertEqual(ast.Name.__doc__, "Name(identifier id, expr_context ctx)")
883 self.assertEqual(
884 ast.cmpop.__doc__,
885 "cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn",
886 )
887 expressions = [f" | {node.__doc__}" for node in ast.expr.__subclasses__()]
888 expressions[0] = f"expr = {ast.expr.__subclasses__()[0].__doc__}"
889 self.assertCountEqual(ast.expr.__doc__.split("\n"), expressions)
890
891 def test_positional_only_feature_version(self):
892 ast.parse("def foo(x, /): ...", feature_version=(3, 8))
893 ast.parse("def bar(x=1, /): ...", feature_version=(3, 8))
894 with self.assertRaises(SyntaxError):
895 ast.parse("def foo(x, /): ...", feature_version=(3, 7))
896 with self.assertRaises(SyntaxError):
897 ast.parse("def bar(x=1, /): ...", feature_version=(3, 7))
898
899 ast.parse("lambda x, /: ...", feature_version=(3, 8))
900 ast.parse("lambda x=1, /: ...", feature_version=(3, 8))
901 with self.assertRaises(SyntaxError):
902 ast.parse("lambda x, /: ...", feature_version=(3, 7))
903 with self.assertRaises(SyntaxError):
904 ast.parse("lambda x=1, /: ...", feature_version=(3, 7))
905
906 def test_assignment_expression_feature_version(self):
907 ast.parse("(x := 0)", feature_version=(3, 8))
908 with self.assertRaises(SyntaxError):
909 ast.parse("(x := 0)", feature_version=(3, 7))
910
911 def test_conditional_context_managers_parse_with_low_feature_version(self):
912 # regression test for gh-115881
913 ast.parse("with (x() if y else z()): ...", feature_version=(3, 8))
914
915 def test_exception_groups_feature_version(self):
916 code = dedent("""
917 try: ...
918 except* Exception: ...
919 """)
920 ast.parse(code)
921 with self.assertRaises(SyntaxError):
922 ast.parse(code, feature_version=(3, 10))
923
924 def test_type_params_feature_version(self):
925 samples = [
926 "type X = int",
927 "class X[T]: pass",
928 "def f[T](): pass",
929 ]
930 for sample in samples:
931 with self.subTest(sample):
932 ast.parse(sample)
933 with self.assertRaises(SyntaxError):
934 ast.parse(sample, feature_version=(3, 11))
935
936 def test_type_params_default_feature_version(self):
937 samples = [
938 "type X[*Ts=int] = int",
939 "class X[T=int]: pass",
940 "def f[**P=int](): pass",
941 ]
942 for sample in samples:
943 with self.subTest(sample):
944 ast.parse(sample)
945 with self.assertRaises(SyntaxError):
946 ast.parse(sample, feature_version=(3, 12))
947
948 def test_invalid_major_feature_version(self):
949 with self.assertRaises(ValueError):
950 ast.parse("pass", feature_version=(2, 7))
951 with self.assertRaises(ValueError):
952 ast.parse("pass", feature_version=(4, 0))
953
954 def test_constant_as_name(self):
955 for constant in "True", "False", "None":
956 expr = ast.Expression(ast.Name(constant, ast.Load()))
957 ast.fix_missing_locations(expr)
958 with self.assertRaisesRegex(
959 ValueError, f"identifier field can't represent '{constant}' constant"
960 ):
961 compile(expr, "<test>", "eval")
962
963 def test_constant_as_unicode_name(self):
964 constants = [
965 ("True", b"Tru\xe1\xb5\x89"),
966 ("False", b"Fal\xc5\xbfe"),
967 ("None", b"N\xc2\xbane"),
968 ]
969 for constant in constants:
970 with self.assertRaisesRegex(ValueError,
971 f"identifier field can't represent '{constant[0]}' constant"):
972 ast.parse(constant[1], mode="eval")
973
974 def test_precedence_enum(self):
975 class _Precedence(enum.IntEnum):
976 """Precedence table that originated from python grammar."""
977
978 NAMED_EXPR = enum.auto() # <target> := <expr1>
979 TUPLE = enum.auto() # <expr1>, <expr2>
980 YIELD = enum.auto() # 'yield', 'yield from'
981 TEST = enum.auto() # 'if'-'else', 'lambda'
982 OR = enum.auto() # 'or'
983 AND = enum.auto() # 'and'
984 NOT = enum.auto() # 'not'
985 CMP = enum.auto() # '<', '>', '==', '>=', '<=', '!=',
986 # 'in', 'not in', 'is', 'is not'
987 EXPR = enum.auto()
988 BOR = EXPR # '|'
989 BXOR = enum.auto() # '^'
990 BAND = enum.auto() # '&'
991 SHIFT = enum.auto() # '<<', '>>'
992 ARITH = enum.auto() # '+', '-'
993 TERM = enum.auto() # '*', '@', '/', '%', '//'
994 FACTOR = enum.auto() # unary '+', '-', '~'
995 POWER = enum.auto() # '**'
996 AWAIT = enum.auto() # 'await'
997 ATOM = enum.auto()
998
999 def next(self):
1000 try:
1001 return self.__class__(self + 1)
1002 except ValueError:
1003 return self
1004
1005 enum._test_simple_enum(_Precedence, ast._Precedence)
1006
1007 @support.cpython_only
1008 def test_ast_recursion_limit(self):
1009 fail_depth = support.exceeds_recursion_limit()
1010 crash_depth = 100_000
1011 success_depth = int(support.get_c_recursion_limit() * 0.8)
1012 if _testinternalcapi is not None:
1013 remaining = _testinternalcapi.get_c_recursion_remaining()
1014 success_depth = min(success_depth, remaining)
1015
1016 def check_limit(prefix, repeated):
1017 expect_ok = prefix + repeated * success_depth
1018 ast.parse(expect_ok)
1019 for depth in (fail_depth, crash_depth):
1020 broken = prefix + repeated * depth
1021 details = "Compiling ({!r} + {!r} * {})".format(prefix, repeated, depth)
1022 with self.assertRaises(RecursionError, msg=details):
1023 with support.infinite_recursion():
1024 ast.parse(broken)
1025
1026 check_limit("a", "()")
1027 check_limit("a", ".b")
1028 check_limit("a", "[0]")
1029 check_limit("a", "*a")
1030
1031 def test_null_bytes(self):
1032 with self.assertRaises(
1033 SyntaxError, msg="source code string cannot contain null bytes"
1034 ):
1035 ast.parse("a\0b")
1036
1037 def assert_none_check(self, node: type[ast.AST], attr: str, source: str) -> None:
1038 with self.subTest(f"{node.__name__}.{attr}"):
1039 tree = ast.parse(source)
1040 found = 0
1041 for child in ast.walk(tree):
1042 if isinstance(child, node):
1043 setattr(child, attr, None)
1044 found += 1
1045 self.assertEqual(found, 1)
1046 e = re.escape(f"field '{attr}' is required for {node.__name__}")
1047 with self.assertRaisesRegex(ValueError, f"^{e}$"):
1048 compile(tree, "<test>", "exec")
1049
1050 def test_none_checks(self) -> None:
1051 tests = [
1052 (ast.alias, "name", "import spam as SPAM"),
1053 (ast.arg, "arg", "def spam(SPAM): spam"),
1054 (ast.comprehension, "target", "[spam for SPAM in spam]"),
1055 (ast.comprehension, "iter", "[spam for spam in SPAM]"),
1056 (ast.keyword, "value", "spam(**SPAM)"),
1057 (ast.match_case, "pattern", "match spam:\n case SPAM: spam"),
1058 (ast.withitem, "context_expr", "with SPAM: spam"),
1059 ]
1060 for node, attr, source in tests:
1061 self.assert_none_check(node, attr, source)
1062
1063
1064 class CopyTests(unittest.TestCase):
1065 """Test copying and pickling AST nodes."""
1066
1067 def test_pickling(self):
1068 import pickle
1069
1070 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1071 for code in exec_tests:
1072 with self.subTest(code=code, protocol=protocol):
1073 tree = compile(code, "?", "exec", 0x400)
1074 ast2 = pickle.loads(pickle.dumps(tree, protocol))
1075 self.assertEqual(to_tuple(ast2), to_tuple(tree))
1076
1077 def test_copy_with_parents(self):
1078 # gh-120108
1079 code = """
1080 ('',)
1081 while i < n:
1082 if ch == '':
1083 ch = format[i]
1084 if ch == '':
1085 if freplace is None:
1086 '' % getattr(object)
1087 elif ch == '':
1088 if zreplace is None:
1089 if hasattr:
1090 offset = object.utcoffset()
1091 if offset is not None:
1092 if offset.days < 0:
1093 offset = -offset
1094 h = divmod(timedelta(hours=0))
1095 if u:
1096 zreplace = '' % (sign,)
1097 elif s:
1098 zreplace = '' % (sign,)
1099 else:
1100 zreplace = '' % (sign,)
1101 elif ch == '':
1102 if Zreplace is None:
1103 Zreplace = ''
1104 if hasattr(object):
1105 s = object.tzname()
1106 if s is not None:
1107 Zreplace = s.replace('')
1108 newformat.append(Zreplace)
1109 else:
1110 push('')
1111 else:
1112 push(ch)
1113
1114 """
1115 tree = ast.parse(textwrap.dedent(code))
1116 for node in ast.walk(tree):
1117 for child in ast.iter_child_nodes(node):
1118 child.parent = node
1119 try:
1120 with support.infinite_recursion(200):
1121 tree2 = copy.deepcopy(tree)
1122 finally:
1123 # Singletons like ast.Load() are shared; make sure we don't
1124 # leave them mutated after this test.
1125 for node in ast.walk(tree):
1126 if hasattr(node, "parent"):
1127 del node.parent
1128
1129 for node in ast.walk(tree2):
1130 for child in ast.iter_child_nodes(node):
1131 if hasattr(child, "parent") and not isinstance(
1132 child,
1133 (
1134 ast.expr_context,
1135 ast.boolop,
1136 ast.unaryop,
1137 ast.cmpop,
1138 ast.operator,
1139 ),
1140 ):
1141 self.assertEqual(to_tuple(child.parent), to_tuple(node))
1142
1143
1144 class ASTHelpers_Test(unittest.TestCase):
1145 maxDiff = None
1146
1147 def test_parse(self):
1148 a = ast.parse("foo(1 + 1)")
1149 b = compile("foo(1 + 1)", "<unknown>", "exec", ast.PyCF_ONLY_AST)
1150 self.assertEqual(ast.dump(a), ast.dump(b))
1151
1152 def test_parse_in_error(self):
1153 try:
1154 1 / 0
1155 except Exception:
1156 with self.assertRaises(SyntaxError) as e:
1157 ast.literal_eval(r"'\U'")
1158 self.assertIsNotNone(e.exception.__context__)
1159
1160 def test_dump(self):
1161 node = ast.parse('spam(eggs, "and cheese")')
1162 self.assertEqual(
1163 ast.dump(node),
1164 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
1165 "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')]))])",
1166 )
1167 self.assertEqual(
1168 ast.dump(node, annotate_fields=False),
1169 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
1170 "Constant('and cheese')]))])",
1171 )
1172 self.assertEqual(
1173 ast.dump(node, include_attributes=True),
1174 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
1175 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), "
1176 "args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, "
1177 "end_lineno=1, end_col_offset=9), Constant(value='and cheese', "
1178 "lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], "
1179 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), "
1180 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24)])",
1181 )
1182
1183 def test_dump_indent(self):
1184 node = ast.parse('spam(eggs, "and cheese")')
1185 self.assertEqual(
1186 ast.dump(node, indent=3),
1187 """\
1188 Module(
1189 body=[
1190 Expr(
1191 value=Call(
1192 func=Name(id='spam', ctx=Load()),
1193 args=[
1194 Name(id='eggs', ctx=Load()),
1195 Constant(value='and cheese')]))])""",
1196 )
1197 self.assertEqual(
1198 ast.dump(node, annotate_fields=False, indent="\t"),
1199 """\
1200 Module(
1201 \t[
1202 \t\tExpr(
1203 \t\t\tCall(
1204 \t\t\t\tName('spam', Load()),
1205 \t\t\t\t[
1206 \t\t\t\t\tName('eggs', Load()),
1207 \t\t\t\t\tConstant('and cheese')]))])""",
1208 )
1209 self.assertEqual(
1210 ast.dump(node, include_attributes=True, indent=3),
1211 """\
1212 Module(
1213 body=[
1214 Expr(
1215 value=Call(
1216 func=Name(
1217 id='spam',
1218 ctx=Load(),
1219 lineno=1,
1220 col_offset=0,
1221 end_lineno=1,
1222 end_col_offset=4),
1223 args=[
1224 Name(
1225 id='eggs',
1226 ctx=Load(),
1227 lineno=1,
1228 col_offset=5,
1229 end_lineno=1,
1230 end_col_offset=9),
1231 Constant(
1232 value='and cheese',
1233 lineno=1,
1234 col_offset=11,
1235 end_lineno=1,
1236 end_col_offset=23)],
1237 lineno=1,
1238 col_offset=0,
1239 end_lineno=1,
1240 end_col_offset=24),
1241 lineno=1,
1242 col_offset=0,
1243 end_lineno=1,
1244 end_col_offset=24)])""",
1245 )
1246
1247 def test_dump_incomplete(self):
1248 node = ast.Raise(lineno=3, col_offset=4)
1249 self.assertEqual(ast.dump(node), "Raise()")
1250 self.assertEqual(
1251 ast.dump(node, include_attributes=True), "Raise(lineno=3, col_offset=4)"
1252 )
1253 node = ast.Raise(exc=ast.Name(id="e", ctx=ast.Load()), lineno=3, col_offset=4)
1254 self.assertEqual(ast.dump(node), "Raise(exc=Name(id='e', ctx=Load()))")
1255 self.assertEqual(
1256 ast.dump(node, annotate_fields=False), "Raise(Name('e', Load()))"
1257 )
1258 self.assertEqual(
1259 ast.dump(node, include_attributes=True),
1260 "Raise(exc=Name(id='e', ctx=Load()), lineno=3, col_offset=4)",
1261 )
1262 self.assertEqual(
1263 ast.dump(node, annotate_fields=False, include_attributes=True),
1264 "Raise(Name('e', Load()), lineno=3, col_offset=4)",
1265 )
1266 node = ast.Raise(cause=ast.Name(id="e", ctx=ast.Load()))
1267 self.assertEqual(ast.dump(node), "Raise(cause=Name(id='e', ctx=Load()))")
1268 self.assertEqual(
1269 ast.dump(node, annotate_fields=False), "Raise(cause=Name('e', Load()))"
1270 )
1271 # Arguments:
1272 node = ast.arguments(args=[ast.arg("x")])
1273 self.assertEqual(
1274 ast.dump(node, annotate_fields=False),
1275 "arguments([], [arg('x')])",
1276 )
1277 node = ast.arguments(posonlyargs=[ast.arg("x")])
1278 self.assertEqual(
1279 ast.dump(node, annotate_fields=False),
1280 "arguments([arg('x')])",
1281 )
1282 node = ast.arguments(posonlyargs=[ast.arg("x")], kwonlyargs=[ast.arg("y")])
1283 self.assertEqual(
1284 ast.dump(node, annotate_fields=False),
1285 "arguments([arg('x')], kwonlyargs=[arg('y')])",
1286 )
1287 node = ast.arguments(args=[ast.arg("x")], kwonlyargs=[ast.arg("y")])
1288 self.assertEqual(
1289 ast.dump(node, annotate_fields=False),
1290 "arguments([], [arg('x')], kwonlyargs=[arg('y')])",
1291 )
1292 node = ast.arguments()
1293 self.assertEqual(
1294 ast.dump(node, annotate_fields=False),
1295 "arguments()",
1296 )
1297 # Classes:
1298 node = ast.ClassDef(
1299 "T",
1300 [],
1301 [ast.keyword("a", ast.Constant(None))],
1302 [],
1303 [ast.Name("dataclass", ctx=ast.Load())],
1304 )
1305 self.assertEqual(
1306 ast.dump(node),
1307 "ClassDef(name='T', keywords=[keyword(arg='a', value=Constant(value=None))], decorator_list=[Name(id='dataclass', ctx=Load())])",
1308 )
1309 self.assertEqual(
1310 ast.dump(node, annotate_fields=False),
1311 "ClassDef('T', [], [keyword('a', Constant(None))], [], [Name('dataclass', Load())])",
1312 )
1313
1314 def test_dump_show_empty(self):
1315 def check_node(node, empty, full, **kwargs):
1316 with self.subTest(show_empty=False):
1317 self.assertEqual(
1318 ast.dump(node, show_empty=False, **kwargs),
1319 empty,
1320 )
1321 with self.subTest(show_empty=True):
1322 self.assertEqual(
1323 ast.dump(node, show_empty=True, **kwargs),
1324 full,
1325 )
1326
1327 def check_text(code, empty, full, **kwargs):
1328 check_node(ast.parse(code), empty, full, **kwargs)
1329
1330 check_node(
1331 ast.arguments(),
1332 empty="arguments()",
1333 full="arguments(posonlyargs=[], args=[], kwonlyargs=[], kw_defaults=[], defaults=[])",
1334 )
1335
1336 check_node(
1337 # Corner case: there are no real `Name` instances with `id=''`:
1338 ast.Name(id="", ctx=ast.Load()),
1339 empty="Name(id='', ctx=Load())",
1340 full="Name(id='', ctx=Load())",
1341 )
1342
1343 check_node(
1344 ast.MatchSingleton(value=None),
1345 empty="MatchSingleton(value=None)",
1346 full="MatchSingleton(value=None)",
1347 )
1348
1349 check_node(
1350 ast.MatchSingleton(value=[]),
1351 empty="MatchSingleton(value=[])",
1352 full="MatchSingleton(value=[])",
1353 )
1354
1355 check_node(
1356 ast.Constant(value=None),
1357 empty="Constant(value=None)",
1358 full="Constant(value=None)",
1359 )
1360
1361 check_node(
1362 ast.Constant(value=[]),
1363 empty="Constant(value=[])",
1364 full="Constant(value=[])",
1365 )
1366
1367 check_node(
1368 ast.Constant(value=""),
1369 empty="Constant(value='')",
1370 full="Constant(value='')",
1371 )
1372
1373 check_text(
1374 "def a(b: int = 0, *, c): ...",
1375 empty="Module(body=[FunctionDef(name='a', args=arguments(args=[arg(arg='b', annotation=Name(id='int', ctx=Load()))], kwonlyargs=[arg(arg='c')], kw_defaults=[None], defaults=[Constant(value=0)]), body=[Expr(value=Constant(value=Ellipsis))])])",
1376 full="Module(body=[FunctionDef(name='a', args=arguments(posonlyargs=[], args=[arg(arg='b', annotation=Name(id='int', ctx=Load()))], kwonlyargs=[arg(arg='c')], kw_defaults=[None], defaults=[Constant(value=0)]), body=[Expr(value=Constant(value=Ellipsis))], decorator_list=[], type_params=[])], type_ignores=[])",
1377 )
1378
1379 check_text(
1380 "def a(b: int = 0, *, c): ...",
1381 empty="Module(body=[FunctionDef(name='a', args=arguments(args=[arg(arg='b', annotation=Name(id='int', ctx=Load(), lineno=1, col_offset=9, end_lineno=1, end_col_offset=12), lineno=1, col_offset=6, end_lineno=1, end_col_offset=12)], kwonlyargs=[arg(arg='c', lineno=1, col_offset=21, end_lineno=1, end_col_offset=22)], kw_defaults=[None], defaults=[Constant(value=0, lineno=1, col_offset=15, end_lineno=1, end_col_offset=16)]), body=[Expr(value=Constant(value=Ellipsis, lineno=1, col_offset=25, end_lineno=1, end_col_offset=28), lineno=1, col_offset=25, end_lineno=1, end_col_offset=28)], lineno=1, col_offset=0, end_lineno=1, end_col_offset=28)])",
1382 full="Module(body=[FunctionDef(name='a', args=arguments(posonlyargs=[], args=[arg(arg='b', annotation=Name(id='int', ctx=Load(), lineno=1, col_offset=9, end_lineno=1, end_col_offset=12), lineno=1, col_offset=6, end_lineno=1, end_col_offset=12)], kwonlyargs=[arg(arg='c', lineno=1, col_offset=21, end_lineno=1, end_col_offset=22)], kw_defaults=[None], defaults=[Constant(value=0, lineno=1, col_offset=15, end_lineno=1, end_col_offset=16)]), body=[Expr(value=Constant(value=Ellipsis, lineno=1, col_offset=25, end_lineno=1, end_col_offset=28), lineno=1, col_offset=25, end_lineno=1, end_col_offset=28)], decorator_list=[], type_params=[], lineno=1, col_offset=0, end_lineno=1, end_col_offset=28)], type_ignores=[])",
1383 include_attributes=True,
1384 )
1385
1386 check_text(
1387 'spam(eggs, "and cheese")',
1388 empty="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')]))])",
1389 full="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], keywords=[]))], type_ignores=[])",
1390 )
1391
1392 check_text(
1393 'spam(eggs, text="and cheese")',
1394 empty="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load())], keywords=[keyword(arg='text', value=Constant(value='and cheese'))]))])",
1395 full="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load())], keywords=[keyword(arg='text', value=Constant(value='and cheese'))]))], type_ignores=[])",
1396 )
1397
1398 check_text(
1399 "import _ast as ast; from module import sub",
1400 empty="Module(body=[Import(names=[alias(name='_ast', asname='ast')]), ImportFrom(module='module', names=[alias(name='sub')], level=0)])",
1401 full="Module(body=[Import(names=[alias(name='_ast', asname='ast')]), ImportFrom(module='module', names=[alias(name='sub')], level=0)], type_ignores=[])",
1402 )
1403
1404 def test_copy_location(self):
1405 src = ast.parse("1 + 1", mode="eval")
1406 src.body.right = ast.copy_location(ast.Constant(2), src.body.right)
1407 self.assertEqual(
1408 ast.dump(src, include_attributes=True),
1409 "Expression(body=BinOp(left=Constant(value=1, lineno=1, col_offset=0, "
1410 "end_lineno=1, end_col_offset=1), op=Add(), right=Constant(value=2, "
1411 "lineno=1, col_offset=4, end_lineno=1, end_col_offset=5), lineno=1, "
1412 "col_offset=0, end_lineno=1, end_col_offset=5))",
1413 )
1414 func = ast.Name("spam", ast.Load())
1415 src = ast.Call(
1416 col_offset=1, lineno=1, end_lineno=1, end_col_offset=1, func=func
1417 )
1418 new = ast.copy_location(src, ast.Call(col_offset=None, lineno=None, func=func))
1419 self.assertIsNone(new.end_lineno)
1420 self.assertIsNone(new.end_col_offset)
1421 self.assertEqual(new.lineno, 1)
1422 self.assertEqual(new.col_offset, 1)
1423
1424 def test_fix_missing_locations(self):
1425 src = ast.parse('write("spam")')
1426 src.body.append(
1427 ast.Expr(ast.Call(ast.Name("spam", ast.Load()), [ast.Constant("eggs")], []))
1428 )
1429 self.assertEqual(src, ast.fix_missing_locations(src))
1430 self.maxDiff = None
1431 self.assertEqual(
1432 ast.dump(src, include_attributes=True),
1433 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
1434 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), "
1435 "args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, "
1436 "end_col_offset=12)], lineno=1, col_offset=0, end_lineno=1, "
1437 "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, "
1438 "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), "
1439 "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), "
1440 "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, "
1441 "end_col_offset=0)], lineno=1, col_offset=0, end_lineno=1, "
1442 "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)])",
1443 )
1444
1445 def test_increment_lineno(self):
1446 src = ast.parse("1 + 1", mode="eval")
1447 self.assertEqual(ast.increment_lineno(src, n=3), src)
1448 self.assertEqual(
1449 ast.dump(src, include_attributes=True),
1450 "Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0, "
1451 "end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, "
1452 "lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, "
1453 "col_offset=0, end_lineno=4, end_col_offset=5))",
1454 )
1455 # issue10869: do not increment lineno of root twice
1456 src = ast.parse("1 + 1", mode="eval")
1457 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
1458 self.assertEqual(
1459 ast.dump(src, include_attributes=True),
1460 "Expression(body=BinOp(left=Constant(value=1, lineno=4, col_offset=0, "
1461 "end_lineno=4, end_col_offset=1), op=Add(), right=Constant(value=1, "
1462 "lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, "
1463 "col_offset=0, end_lineno=4, end_col_offset=5))",
1464 )
1465 src = ast.Call(
1466 func=ast.Name("test", ast.Load()), args=[], keywords=[], lineno=1
1467 )
1468 self.assertEqual(ast.increment_lineno(src).lineno, 2)
1469 self.assertIsNone(ast.increment_lineno(src).end_lineno)
1470
1471 def test_increment_lineno_on_module(self):
1472 src = ast.parse(
1473 dedent("""\
1474 a = 1
1475 b = 2 # type: ignore
1476 c = 3
1477 d = 4 # type: ignore@tag
1478 """),
1479 type_comments=True,
1480 )
1481 ast.increment_lineno(src, n=5)
1482 self.assertEqual(src.type_ignores[0].lineno, 7)
1483 self.assertEqual(src.type_ignores[1].lineno, 9)
1484 self.assertEqual(src.type_ignores[1].tag, "@tag")
1485
1486 def test_iter_fields(self):
1487 node = ast.parse("foo()", mode="eval")
1488 d = dict(ast.iter_fields(node.body))
1489 self.assertEqual(d.pop("func").id, "foo")
1490 self.assertEqual(d, {"keywords": [], "args": []})
1491
1492 def test_iter_child_nodes(self):
1493 node = ast.parse("spam(23, 42, eggs='leek')", mode="eval")
1494 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
1495 iterator = ast.iter_child_nodes(node.body)
1496 self.assertEqual(next(iterator).id, "spam")
1497 self.assertEqual(next(iterator).value, 23)
1498 self.assertEqual(next(iterator).value, 42)
1499 self.assertEqual(
1500 ast.dump(next(iterator)),
1501 "keyword(arg='eggs', value=Constant(value='leek'))",
1502 )
1503
1504 def test_get_docstring(self):
1505 node = ast.parse('"""line one\n line two"""')
1506 self.assertEqual(ast.get_docstring(node), "line one\nline two")
1507
1508 node = ast.parse('class foo:\n """line one\n line two"""')
1509 self.assertEqual(ast.get_docstring(node.body[0]), "line one\nline two")
1510
1511 node = ast.parse('def foo():\n """line one\n line two"""')
1512 self.assertEqual(ast.get_docstring(node.body[0]), "line one\nline two")
1513
1514 node = ast.parse('async def foo():\n """spam\n ham"""')
1515 self.assertEqual(ast.get_docstring(node.body[0]), "spam\nham")
1516
1517 node = ast.parse('async def foo():\n """spam\n ham"""')
1518 self.assertEqual(ast.get_docstring(node.body[0], clean=False), "spam\n ham")
1519
1520 node = ast.parse("x")
1521 self.assertRaises(TypeError, ast.get_docstring, node.body[0])
1522
1523 def test_get_docstring_none(self):
1524 self.assertIsNone(ast.get_docstring(ast.parse("")))
1525 node = ast.parse('x = "not docstring"')
1526 self.assertIsNone(ast.get_docstring(node))
1527 node = ast.parse("def foo():\n pass")
1528 self.assertIsNone(ast.get_docstring(node))
1529
1530 node = ast.parse("class foo:\n pass")
1531 self.assertIsNone(ast.get_docstring(node.body[0]))
1532 node = ast.parse('class foo:\n x = "not docstring"')
1533 self.assertIsNone(ast.get_docstring(node.body[0]))
1534 node = ast.parse("class foo:\n def bar(self): pass")
1535 self.assertIsNone(ast.get_docstring(node.body[0]))
1536
1537 node = ast.parse("def foo():\n pass")
1538 self.assertIsNone(ast.get_docstring(node.body[0]))
1539 node = ast.parse('def foo():\n x = "not docstring"')
1540 self.assertIsNone(ast.get_docstring(node.body[0]))
1541
1542 node = ast.parse("async def foo():\n pass")
1543 self.assertIsNone(ast.get_docstring(node.body[0]))
1544 node = ast.parse('async def foo():\n x = "not docstring"')
1545 self.assertIsNone(ast.get_docstring(node.body[0]))
1546
1547 node = ast.parse("async def foo():\n 42")
1548 self.assertIsNone(ast.get_docstring(node.body[0]))
1549
1550 def test_multi_line_docstring_col_offset_and_lineno_issue16806(self):
1551 node = ast.parse(
1552 '"""line one\nline two"""\n\n'
1553 'def foo():\n """line one\n line two"""\n\n'
1554 ' def bar():\n """line one\n line two"""\n'
1555 ' """line one\n line two"""\n'
1556 '"""line one\nline two"""\n\n'
1557 )
1558 self.assertEqual(node.body[0].col_offset, 0)
1559 self.assertEqual(node.body[0].lineno, 1)
1560 self.assertEqual(node.body[1].body[0].col_offset, 2)
1561 self.assertEqual(node.body[1].body[0].lineno, 5)
1562 self.assertEqual(node.body[1].body[1].body[0].col_offset, 4)
1563 self.assertEqual(node.body[1].body[1].body[0].lineno, 9)
1564 self.assertEqual(node.body[1].body[2].col_offset, 2)
1565 self.assertEqual(node.body[1].body[2].lineno, 11)
1566 self.assertEqual(node.body[2].col_offset, 0)
1567 self.assertEqual(node.body[2].lineno, 13)
1568
1569 def test_elif_stmt_start_position(self):
1570 node = ast.parse("if a:\n pass\nelif b:\n pass\n")
1571 elif_stmt = node.body[0].orelse[0]
1572 self.assertEqual(elif_stmt.lineno, 3)
1573 self.assertEqual(elif_stmt.col_offset, 0)
1574
1575 def test_elif_stmt_start_position_with_else(self):
1576 node = ast.parse("if a:\n pass\nelif b:\n pass\nelse:\n pass\n")
1577 elif_stmt = node.body[0].orelse[0]
1578 self.assertEqual(elif_stmt.lineno, 3)
1579 self.assertEqual(elif_stmt.col_offset, 0)
1580
1581 def test_starred_expr_end_position_within_call(self):
1582 node = ast.parse("f(*[0, 1])")
1583 starred_expr = node.body[0].value.args[0]
1584 self.assertEqual(starred_expr.end_lineno, 1)
1585 self.assertEqual(starred_expr.end_col_offset, 9)
1586
1587 def test_literal_eval(self):
1588 self.assertEqual(ast.literal_eval("[1, 2, 3]"), [1, 2, 3])
1589 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
1590 self.assertEqual(ast.literal_eval("(True, False, None)"), (True, False, None))
1591 self.assertEqual(ast.literal_eval("{1, 2, 3}"), {1, 2, 3})
1592 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
1593 self.assertEqual(ast.literal_eval("set()"), set())
1594 self.assertRaises(ValueError, ast.literal_eval, "foo()")
1595 self.assertEqual(ast.literal_eval("6"), 6)
1596 self.assertEqual(ast.literal_eval("+6"), 6)
1597 self.assertEqual(ast.literal_eval("-6"), -6)
1598 self.assertEqual(ast.literal_eval("3.25"), 3.25)
1599 self.assertEqual(ast.literal_eval("+3.25"), 3.25)
1600 self.assertEqual(ast.literal_eval("-3.25"), -3.25)
1601 self.assertEqual(repr(ast.literal_eval("-0.0")), "-0.0")
1602 self.assertRaises(ValueError, ast.literal_eval, "++6")
1603 self.assertRaises(ValueError, ast.literal_eval, "+True")
1604 self.assertRaises(ValueError, ast.literal_eval, "2+3")
1605
1606 def test_literal_eval_str_int_limit(self):
1607 with support.adjust_int_max_str_digits(4000):
1608 ast.literal_eval("3" * 4000) # no error
1609 with self.assertRaises(SyntaxError) as err_ctx:
1610 ast.literal_eval("3" * 4001)
1611 self.assertIn("Exceeds the limit ", str(err_ctx.exception))
1612 self.assertIn(" Consider hexadecimal ", str(err_ctx.exception))
1613
1614 def test_literal_eval_complex(self):
1615 # Issue #4907
1616 self.assertEqual(ast.literal_eval("6j"), 6j)
1617 self.assertEqual(ast.literal_eval("-6j"), -6j)
1618 self.assertEqual(ast.literal_eval("6.75j"), 6.75j)
1619 self.assertEqual(ast.literal_eval("-6.75j"), -6.75j)
1620 self.assertEqual(ast.literal_eval("3+6j"), 3 + 6j)
1621 self.assertEqual(ast.literal_eval("-3+6j"), -3 + 6j)
1622 self.assertEqual(ast.literal_eval("3-6j"), 3 - 6j)
1623 self.assertEqual(ast.literal_eval("-3-6j"), -3 - 6j)
1624 self.assertEqual(ast.literal_eval("3.25+6.75j"), 3.25 + 6.75j)
1625 self.assertEqual(ast.literal_eval("-3.25+6.75j"), -3.25 + 6.75j)
1626 self.assertEqual(ast.literal_eval("3.25-6.75j"), 3.25 - 6.75j)
1627 self.assertEqual(ast.literal_eval("-3.25-6.75j"), -3.25 - 6.75j)
1628 self.assertEqual(ast.literal_eval("(3+6j)"), 3 + 6j)
1629 self.assertRaises(ValueError, ast.literal_eval, "-6j+3")
1630 self.assertRaises(ValueError, ast.literal_eval, "-6j+3j")
1631 self.assertRaises(ValueError, ast.literal_eval, "3+-6j")
1632 self.assertRaises(ValueError, ast.literal_eval, "3+(0+6j)")
1633 self.assertRaises(ValueError, ast.literal_eval, "-(3+6j)")
1634
1635 def test_literal_eval_malformed_dict_nodes(self):
1636 malformed = ast.Dict(
1637 keys=[ast.Constant(1), ast.Constant(2)], values=[ast.Constant(3)]
1638 )
1639 self.assertRaises(ValueError, ast.literal_eval, malformed)
1640 malformed = ast.Dict(
1641 keys=[ast.Constant(1)], values=[ast.Constant(2), ast.Constant(3)]
1642 )
1643 self.assertRaises(ValueError, ast.literal_eval, malformed)
1644
1645 def test_literal_eval_trailing_ws(self):
1646 self.assertEqual(ast.literal_eval(" -1"), -1)
1647 self.assertEqual(ast.literal_eval("\t\t-1"), -1)
1648 self.assertEqual(ast.literal_eval(" \t -1"), -1)
1649 self.assertRaises(IndentationError, ast.literal_eval, "\n -1")
1650
1651 def test_literal_eval_malformed_lineno(self):
1652 msg = r"malformed node or string on line 3:"
1653 with self.assertRaisesRegex(ValueError, msg):
1654 ast.literal_eval("{'a': 1,\n'b':2,\n'c':++3,\n'd':4}")
1655
1656 node = ast.UnaryOp(ast.UAdd(), ast.UnaryOp(ast.UAdd(), ast.Constant(6)))
1657 self.assertIsNone(getattr(node, "lineno", None))
1658 msg = r"malformed node or string:"
1659 with self.assertRaisesRegex(ValueError, msg):
1660 ast.literal_eval(node)
1661
1662 def test_literal_eval_syntax_errors(self):
1663 with self.assertRaisesRegex(SyntaxError, "unexpected indent"):
1664 ast.literal_eval(r"""
1665 \
1666 (\
1667 \ """)
1668
1669 def test_bad_integer(self):
1670 # issue13436: Bad error message with invalid numeric values
1671 body = [
1672 ast.ImportFrom(
1673 module="time",
1674 names=[ast.alias(name="sleep")],
1675 level=None,
1676 lineno=None,
1677 col_offset=None,
1678 )
1679 ]
1680 mod = ast.Module(body, [])
1681 with self.assertRaises(ValueError) as cm:
1682 compile(mod, "test", "exec")
1683 self.assertIn("invalid integer value: None", str(cm.exception))
1684
1685 def test_level_as_none(self):
1686 body = [
1687 ast.ImportFrom(
1688 module="time",
1689 names=[ast.alias(name="sleep", lineno=0, col_offset=0)],
1690 level=None,
1691 lineno=0,
1692 col_offset=0,
1693 )
1694 ]
1695 mod = ast.Module(body, [])
1696 code = compile(mod, "test", "exec")
1697 ns = {}
1698 exec(code, ns)
1699 self.assertIn("sleep", ns)
1700
1701 def test_recursion_direct(self):
1702 e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0, operand=ast.Constant(1))
1703 e.operand = e
1704 with self.assertRaises(RecursionError):
1705 with support.infinite_recursion():
1706 compile(ast.Expression(e), "<test>", "eval")
1707
1708 def test_recursion_indirect(self):
1709 e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0, operand=ast.Constant(1))
1710 f = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0, operand=ast.Constant(1))
1711 e.operand = f
1712 f.operand = e
1713 with self.assertRaises(RecursionError):
1714 with support.infinite_recursion():
1715 compile(ast.Expression(e), "<test>", "eval")
1716
1717
1718 class ASTValidatorTests(unittest.TestCase):
1719 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
1720 mod.lineno = mod.col_offset = 0
1721 ast.fix_missing_locations(mod)
1722 if msg is None:
1723 compile(mod, "<test>", mode)
1724 else:
1725 with self.assertRaises(exc) as cm:
1726 compile(mod, "<test>", mode)
1727 self.assertIn(msg, str(cm.exception))
1728
1729 def expr(self, node, msg=None, *, exc=ValueError):
1730 mod = ast.Module([ast.Expr(node)], [])
1731 self.mod(mod, msg, exc=exc)
1732
1733 def stmt(self, stmt, msg=None):
1734 mod = ast.Module([stmt], [])
1735 self.mod(mod, msg)
1736
1737 def test_module(self):
1738 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
1739 self.mod(m, "must have Load context", "single")
1740 m = ast.Expression(ast.Name("x", ast.Store()))
1741 self.mod(m, "must have Load context", "eval")
1742
1743 def _check_arguments(self, fac, check):
1744 def arguments(
1745 args=None,
1746 posonlyargs=None,
1747 vararg=None,
1748 kwonlyargs=None,
1749 kwarg=None,
1750 defaults=None,
1751 kw_defaults=None,
1752 ):
1753 if args is None:
1754 args = []
1755 if posonlyargs is None:
1756 posonlyargs = []
1757 if kwonlyargs is None:
1758 kwonlyargs = []
1759 if defaults is None:
1760 defaults = []
1761 if kw_defaults is None:
1762 kw_defaults = []
1763 args = ast.arguments(
1764 args, posonlyargs, vararg, kwonlyargs, kw_defaults, kwarg, defaults
1765 )
1766 return fac(args)
1767
1768 args = [ast.arg("x", ast.Name("x", ast.Store()))]
1769 check(arguments(args=args), "must have Load context")
1770 check(arguments(posonlyargs=args), "must have Load context")
1771 check(arguments(kwonlyargs=args), "must have Load context")
1772 check(
1773 arguments(defaults=[ast.Constant(3)]), "more positional defaults than args"
1774 )
1775 check(
1776 arguments(kw_defaults=[ast.Constant(4)]),
1777 "length of kwonlyargs is not the same as kw_defaults",
1778 )
1779 args = [ast.arg("x", ast.Name("x", ast.Load()))]
1780 check(
1781 arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
1782 "must have Load context",
1783 )
1784 args = [
1785 ast.arg("a", ast.Name("x", ast.Load())),
1786 ast.arg("b", ast.Name("y", ast.Load())),
1787 ]
1788 check(
1789 arguments(kwonlyargs=args, kw_defaults=[None, ast.Name("x", ast.Store())]),
1790 "must have Load context",
1791 )
1792
1793 def test_funcdef(self):
1794 a = ast.arguments([], [], None, [], [], None, [])
1795 f = ast.FunctionDef("x", a, [], [], None, None, [])
1796 self.stmt(f, "empty body on FunctionDef")
1797 f = ast.FunctionDef(
1798 "x", a, [ast.Pass()], [ast.Name("x", ast.Store())], None, None, []
1799 )
1800 self.stmt(f, "must have Load context")
1801 f = ast.FunctionDef(
1802 "x", a, [ast.Pass()], [], ast.Name("x", ast.Store()), None, []
1803 )
1804 self.stmt(f, "must have Load context")
1805 f = ast.FunctionDef("x", ast.arguments(), [ast.Pass()])
1806 self.stmt(f)
1807
1808 def fac(args):
1809 return ast.FunctionDef("x", args, [ast.Pass()], [], None, None, [])
1810
1811 self._check_arguments(fac, self.stmt)
1812
1813 def test_funcdef_pattern_matching(self):
1814 # gh-104799: New fields on FunctionDef should be added at the end
1815 def matcher(node):
1816 match node:
1817 case ast.FunctionDef(
1818 "foo",
1819 ast.arguments(args=[ast.arg("bar")]),
1820 [ast.Pass()],
1821 [ast.Name("capybara", ast.Load())],
1822 ast.Name("pacarana", ast.Load()),
1823 ):
1824 return True
1825 case _:
1826 return False
1827
1828 code = """
1829 @capybara
1830 def foo(bar) -> pacarana:
1831 pass
1832 """
1833 source = ast.parse(textwrap.dedent(code))
1834 funcdef = source.body[0]
1835 self.assertIsInstance(funcdef, ast.FunctionDef)
1836 self.assertTrue(matcher(funcdef))
1837
1838 def test_classdef(self):
1839 def cls(
1840 bases=None, keywords=None, body=None, decorator_list=None, type_params=None
1841 ):
1842 if bases is None:
1843 bases = []
1844 if keywords is None:
1845 keywords = []
1846 if body is None:
1847 body = [ast.Pass()]
1848 if decorator_list is None:
1849 decorator_list = []
1850 if type_params is None:
1851 type_params = []
1852 return ast.ClassDef(
1853 "myclass", bases, keywords, body, decorator_list, type_params
1854 )
1855
1856 self.stmt(cls(bases=[ast.Name("x", ast.Store())]), "must have Load context")
1857 self.stmt(
1858 cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
1859 "must have Load context",
1860 )
1861 self.stmt(cls(body=[]), "empty body on ClassDef")
1862 self.stmt(cls(body=[None]), "None disallowed")
1863 self.stmt(
1864 cls(decorator_list=[ast.Name("x", ast.Store())]), "must have Load context"
1865 )
1866
1867 def test_delete(self):
1868 self.stmt(ast.Delete([]), "empty targets on Delete")
1869 self.stmt(ast.Delete([None]), "None disallowed")
1870 self.stmt(ast.Delete([ast.Name("x", ast.Load())]), "must have Del context")
1871
1872 def test_assign(self):
1873 self.stmt(ast.Assign([], ast.Constant(3)), "empty targets on Assign")
1874 self.stmt(ast.Assign([None], ast.Constant(3)), "None disallowed")
1875 self.stmt(
1876 ast.Assign([ast.Name("x", ast.Load())], ast.Constant(3)),
1877 "must have Store context",
1878 )
1879 self.stmt(
1880 ast.Assign([ast.Name("x", ast.Store())], ast.Name("y", ast.Store())),
1881 "must have Load context",
1882 )
1883
1884 def test_augassign(self):
1885 aug = ast.AugAssign(
1886 ast.Name("x", ast.Load()), ast.Add(), ast.Name("y", ast.Load())
1887 )
1888 self.stmt(aug, "must have Store context")
1889 aug = ast.AugAssign(
1890 ast.Name("x", ast.Store()), ast.Add(), ast.Name("y", ast.Store())
1891 )
1892 self.stmt(aug, "must have Load context")
1893
1894 def test_for(self):
1895 x = ast.Name("x", ast.Store())
1896 y = ast.Name("y", ast.Load())
1897 p = ast.Pass()
1898 self.stmt(ast.For(x, y, [], []), "empty body on For")
1899 self.stmt(
1900 ast.For(ast.Name("x", ast.Load()), y, [p], []), "must have Store context"
1901 )
1902 self.stmt(
1903 ast.For(x, ast.Name("y", ast.Store()), [p], []), "must have Load context"
1904 )
1905 e = ast.Expr(ast.Name("x", ast.Store()))
1906 self.stmt(ast.For(x, y, [e], []), "must have Load context")
1907 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
1908
1909 def test_while(self):
1910 self.stmt(ast.While(ast.Constant(3), [], []), "empty body on While")
1911 self.stmt(
1912 ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
1913 "must have Load context",
1914 )
1915 self.stmt(
1916 ast.While(
1917 ast.Constant(3), [ast.Pass()], [ast.Expr(ast.Name("x", ast.Store()))]
1918 ),
1919 "must have Load context",
1920 )
1921
1922 def test_if(self):
1923 self.stmt(ast.If(ast.Constant(3), [], []), "empty body on If")
1924 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
1925 self.stmt(i, "must have Load context")
1926 i = ast.If(ast.Constant(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
1927 self.stmt(i, "must have Load context")
1928 i = ast.If(
1929 ast.Constant(3), [ast.Pass()], [ast.Expr(ast.Name("x", ast.Store()))]
1930 )
1931 self.stmt(i, "must have Load context")
1932
1933 def test_with(self):
1934 p = ast.Pass()
1935 self.stmt(ast.With([], [p]), "empty items on With")
1936 i = ast.withitem(ast.Constant(3), None)
1937 self.stmt(ast.With([i], []), "empty body on With")
1938 i = ast.withitem(ast.Name("x", ast.Store()), None)
1939 self.stmt(ast.With([i], [p]), "must have Load context")
1940 i = ast.withitem(ast.Constant(3), ast.Name("x", ast.Load()))
1941 self.stmt(ast.With([i], [p]), "must have Store context")
1942
1943 def test_raise(self):
1944 r = ast.Raise(None, ast.Constant(3))
1945 self.stmt(r, "Raise with cause but no exception")
1946 r = ast.Raise(ast.Name("x", ast.Store()), None)
1947 self.stmt(r, "must have Load context")
1948 r = ast.Raise(ast.Constant(4), ast.Name("x", ast.Store()))
1949 self.stmt(r, "must have Load context")
1950
1951 def test_try(self):
1952 p = ast.Pass()
1953 t = ast.Try([], [], [], [p])
1954 self.stmt(t, "empty body on Try")
1955 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
1956 self.stmt(t, "must have Load context")
1957 t = ast.Try([p], [], [], [])
1958 self.stmt(t, "Try has neither except handlers nor finalbody")
1959 t = ast.Try([p], [], [p], [p])
1960 self.stmt(t, "Try has orelse but no except handlers")
1961 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
1962 self.stmt(t, "empty body on ExceptHandler")
1963 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
1964 self.stmt(ast.Try([p], e, [], []), "must have Load context")
1965 e = [ast.ExceptHandler(None, "x", [p])]
1966 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
1967 self.stmt(t, "must have Load context")
1968 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
1969 self.stmt(t, "must have Load context")
1970
1971 def test_try_star(self):
1972 p = ast.Pass()
1973 t = ast.TryStar([], [], [], [p])
1974 self.stmt(t, "empty body on TryStar")
1975 t = ast.TryStar([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
1976 self.stmt(t, "must have Load context")
1977 t = ast.TryStar([p], [], [], [])
1978 self.stmt(t, "TryStar has neither except handlers nor finalbody")
1979 t = ast.TryStar([p], [], [p], [p])
1980 self.stmt(t, "TryStar has orelse but no except handlers")
1981 t = ast.TryStar([p], [ast.ExceptHandler(None, "x", [])], [], [])
1982 self.stmt(t, "empty body on ExceptHandler")
1983 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
1984 self.stmt(ast.TryStar([p], e, [], []), "must have Load context")
1985 e = [ast.ExceptHandler(None, "x", [p])]
1986 t = ast.TryStar([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
1987 self.stmt(t, "must have Load context")
1988 t = ast.TryStar([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
1989 self.stmt(t, "must have Load context")
1990
1991 def test_assert(self):
1992 self.stmt(
1993 ast.Assert(ast.Name("x", ast.Store()), None), "must have Load context"
1994 )
1995 assrt = ast.Assert(ast.Name("x", ast.Load()), ast.Name("y", ast.Store()))
1996 self.stmt(assrt, "must have Load context")
1997
1998 def test_import(self):
1999 self.stmt(ast.Import([]), "empty names on Import")
2000
2001 def test_importfrom(self):
2002 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
2003 self.stmt(imp, "Negative ImportFrom level")
2004 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
2005
2006 def test_global(self):
2007 self.stmt(ast.Global([]), "empty names on Global")
2008
2009 def test_nonlocal(self):
2010 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
2011
2012 def test_expr(self):
2013 e = ast.Expr(ast.Name("x", ast.Store()))
2014 self.stmt(e, "must have Load context")
2015
2016 def test_boolop(self):
2017 b = ast.BoolOp(ast.And(), [])
2018 self.expr(b, "less than 2 values")
2019 b = ast.BoolOp(ast.And(), [ast.Constant(3)])
2020 self.expr(b, "less than 2 values")
2021 b = ast.BoolOp(ast.And(), [ast.Constant(4), None])
2022 self.expr(b, "None disallowed")
2023 b = ast.BoolOp(ast.And(), [ast.Constant(4), ast.Name("x", ast.Store())])
2024 self.expr(b, "must have Load context")
2025
2026 def test_unaryop(self):
2027 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
2028 self.expr(u, "must have Load context")
2029
2030 def test_lambda(self):
2031 a = ast.arguments([], [], None, [], [], None, [])
2032 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())), "must have Load context")
2033
2034 def fac(args):
2035 return ast.Lambda(args, ast.Name("x", ast.Load()))
2036
2037 self._check_arguments(fac, self.expr)
2038
2039 def test_ifexp(self):
2040 l = ast.Name("x", ast.Load())
2041 s = ast.Name("y", ast.Store())
2042 for args in (s, l, l), (l, s, l), (l, l, s):
2043 self.expr(ast.IfExp(*args), "must have Load context")
2044
2045 def test_dict(self):
2046 d = ast.Dict([], [ast.Name("x", ast.Load())])
2047 self.expr(d, "same number of keys as values")
2048 d = ast.Dict([ast.Name("x", ast.Load())], [None])
2049 self.expr(d, "None disallowed")
2050
2051 def test_set(self):
2052 self.expr(ast.Set([None]), "None disallowed")
2053 s = ast.Set([ast.Name("x", ast.Store())])
2054 self.expr(s, "must have Load context")
2055
2056 def _check_comprehension(self, fac):
2057 self.expr(fac([]), "comprehension with no generators")
2058 g = ast.comprehension(
2059 ast.Name("x", ast.Load()), ast.Name("x", ast.Load()), [], 0
2060 )
2061 self.expr(fac([g]), "must have Store context")
2062 g = ast.comprehension(
2063 ast.Name("x", ast.Store()), ast.Name("x", ast.Store()), [], 0
2064 )
2065 self.expr(fac([g]), "must have Load context")
2066 x = ast.Name("x", ast.Store())
2067 y = ast.Name("y", ast.Load())
2068 g = ast.comprehension(x, y, [None], 0)
2069 self.expr(fac([g]), "None disallowed")
2070 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())], 0)
2071 self.expr(fac([g]), "must have Load context")
2072
2073 def _simple_comp(self, fac):
2074 g = ast.comprehension(
2075 ast.Name("x", ast.Store()), ast.Name("x", ast.Load()), [], 0
2076 )
2077 self.expr(fac(ast.Name("x", ast.Store()), [g]), "must have Load context")
2078
2079 def wrap(gens):
2080 return fac(ast.Name("x", ast.Store()), gens)
2081
2082 self._check_comprehension(wrap)
2083
2084 def test_listcomp(self):
2085 self._simple_comp(ast.ListComp)
2086
2087 def test_setcomp(self):
2088 self._simple_comp(ast.SetComp)
2089
2090 def test_generatorexp(self):
2091 self._simple_comp(ast.GeneratorExp)
2092
2093 def test_dictcomp(self):
2094 g = ast.comprehension(
2095 ast.Name("y", ast.Store()), ast.Name("p", ast.Load()), [], 0
2096 )
2097 c = ast.DictComp(ast.Name("x", ast.Store()), ast.Name("y", ast.Load()), [g])
2098 self.expr(c, "must have Load context")
2099 c = ast.DictComp(ast.Name("x", ast.Load()), ast.Name("y", ast.Store()), [g])
2100 self.expr(c, "must have Load context")
2101
2102 def factory(comps):
2103 k = ast.Name("x", ast.Load())
2104 v = ast.Name("y", ast.Load())
2105 return ast.DictComp(k, v, comps)
2106
2107 self._check_comprehension(factory)
2108
2109 def test_yield(self):
2110 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
2111 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
2112
2113 def test_compare(self):
2114 left = ast.Name("x", ast.Load())
2115 comp = ast.Compare(left, [ast.In()], [])
2116 self.expr(comp, "no comparators")
2117 comp = ast.Compare(left, [ast.In()], [ast.Constant(4), ast.Constant(5)])
2118 self.expr(comp, "different number of comparators and operands")
2119 comp = ast.Compare(ast.Constant("blah"), [ast.In()], [left])
2120 self.expr(comp)
2121 comp = ast.Compare(left, [ast.In()], [ast.Constant("blah")])
2122 self.expr(comp)
2123
2124 def test_call(self):
2125 func = ast.Name("x", ast.Load())
2126 args = [ast.Name("y", ast.Load())]
2127 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
2128 call = ast.Call(ast.Name("x", ast.Store()), args, keywords)
2129 self.expr(call, "must have Load context")
2130 call = ast.Call(func, [None], keywords)
2131 self.expr(call, "None disallowed")
2132 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
2133 call = ast.Call(func, args, bad_keywords)
2134 self.expr(call, "must have Load context")
2135
2136 def test_num(self):
2137 with warnings.catch_warnings(record=True) as wlog:
2138 warnings.filterwarnings("ignore", "", DeprecationWarning)
2139 from ast import Num
2140
2141 with warnings.catch_warnings(record=True) as wlog:
2142 warnings.filterwarnings("always", "", DeprecationWarning)
2143
2144 class subint(int):
2145 pass
2146
2147 class subfloat(float):
2148 pass
2149
2150 class subcomplex(complex):
2151 pass
2152
2153 for obj in "0", "hello":
2154 self.expr(ast.Num(obj))
2155 for obj in subint(), subfloat(), subcomplex():
2156 self.expr(ast.Num(obj), "invalid type", exc=TypeError)
2157
2158 self.assertEqual(
2159 [str(w.message) for w in wlog],
2160 [
2161 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
2162 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
2163 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
2164 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
2165 "ast.Num is deprecated and will be removed in Python 3.14; use ast.Constant instead",
2166 ],
2167 )
2168
2169 def test_attribute(self):
2170 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
2171 self.expr(attr, "must have Load context")
2172
2173 def test_subscript(self):
2174 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Constant(3), ast.Load())
2175 self.expr(sub, "must have Load context")
2176 x = ast.Name("x", ast.Load())
2177 sub = ast.Subscript(x, ast.Name("y", ast.Store()), ast.Load())
2178 self.expr(sub, "must have Load context")
2179 s = ast.Name("x", ast.Store())
2180 for args in (s, None, None), (None, s, None), (None, None, s):
2181 sl = ast.Slice(*args)
2182 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
2183 sl = ast.Tuple([], ast.Load())
2184 self.expr(ast.Subscript(x, sl, ast.Load()))
2185 sl = ast.Tuple([s], ast.Load())
2186 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
2187
2188 def test_starred(self):
2189 left = ast.List(
2190 [ast.Starred(ast.Name("x", ast.Load()), ast.Store())], ast.Store()
2191 )
2192 assign = ast.Assign([left], ast.Constant(4))
2193 self.stmt(assign, "must have Store context")
2194
2195 def _sequence(self, fac):
2196 self.expr(fac([None], ast.Load()), "None disallowed")
2197 self.expr(
2198 fac([ast.Name("x", ast.Store())], ast.Load()), "must have Load context"
2199 )
2200
2201 def test_list(self):
2202 self._sequence(ast.List)
2203
2204 def test_tuple(self):
2205 self._sequence(ast.Tuple)
2206
2207 def test_nameconstant(self):
2208 with warnings.catch_warnings(record=True) as wlog:
2209 warnings.filterwarnings("ignore", "", DeprecationWarning)
2210 from ast import NameConstant
2211
2212 with warnings.catch_warnings(record=True) as wlog:
2213 warnings.filterwarnings("always", "", DeprecationWarning)
2214 self.expr(ast.NameConstant(4))
2215
2216 self.assertEqual(
2217 [str(w.message) for w in wlog],
2218 [
2219 "ast.NameConstant is deprecated and will be removed in Python 3.14; use ast.Constant instead",
2220 ],
2221 )
2222
2223 @support.requires_resource("cpu")
2224 def test_stdlib_validates(self):
2225 stdlib = os.path.dirname(ast.__file__)
2226 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
2227 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
2228 for module in tests:
2229 with self.subTest(module):
2230 fn = os.path.join(stdlib, module)
2231 with open(fn, "r", encoding="utf-8") as fp:
2232 source = fp.read()
2233 mod = ast.parse(source, fn)
2234 compile(mod, fn, "exec")
2235
2236 constant_1 = ast.Constant(1)
2237 pattern_1 = ast.MatchValue(constant_1)
2238
2239 constant_x = ast.Constant("x")
2240 pattern_x = ast.MatchValue(constant_x)
2241
2242 constant_true = ast.Constant(True)
2243 pattern_true = ast.MatchSingleton(True)
2244
2245 name_carter = ast.Name("carter", ast.Load())
2246
2247 _MATCH_PATTERNS = [
2248 ast.MatchValue(
2249 ast.Attribute(
2250 ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load()),
2251 "z",
2252 ast.Load(),
2253 )
2254 ),
2255 ast.MatchValue(
2256 ast.Attribute(
2257 ast.Attribute(ast.Name("x", ast.Load()), "y", ast.Store()),
2258 "z",
2259 ast.Load(),
2260 )
2261 ),
2262 ast.MatchValue(ast.Constant(...)),
2263 ast.MatchValue(ast.Constant(True)),
2264 ast.MatchValue(ast.Constant((1, 2, 3))),
2265 ast.MatchSingleton("string"),
2266 ast.MatchSequence([ast.MatchSingleton("string")]),
2267 ast.MatchSequence([ast.MatchSequence([ast.MatchSingleton("string")])]),
2268 ast.MatchMapping([constant_1, constant_true], [pattern_x]),
2269 ast.MatchMapping(
2270 [constant_true, constant_1], [pattern_x, pattern_1], rest="True"
2271 ),
2272 ast.MatchMapping(
2273 [constant_true, ast.Starred(ast.Name("lol", ast.Load()), ast.Load())],
2274 [pattern_x, pattern_1],
2275 rest="legit",
2276 ),
2277 ast.MatchClass(
2278 ast.Attribute(ast.Attribute(constant_x, "y", ast.Load()), "z", ast.Load()),
2279 patterns=[],
2280 kwd_attrs=[],
2281 kwd_patterns=[],
2282 ),
2283 ast.MatchClass(
2284 name_carter, patterns=[], kwd_attrs=["True"], kwd_patterns=[pattern_1]
2285 ),
2286 ast.MatchClass(
2287 name_carter, patterns=[], kwd_attrs=[], kwd_patterns=[pattern_1]
2288 ),
2289 ast.MatchClass(
2290 name_carter,
2291 patterns=[ast.MatchSingleton("string")],
2292 kwd_attrs=[],
2293 kwd_patterns=[],
2294 ),
2295 ast.MatchClass(
2296 name_carter, patterns=[ast.MatchStar()], kwd_attrs=[], kwd_patterns=[]
2297 ),
2298 ast.MatchClass(
2299 name_carter, patterns=[], kwd_attrs=[], kwd_patterns=[ast.MatchStar()]
2300 ),
2301 ast.MatchClass(
2302 constant_true, # invalid name
2303 patterns=[],
2304 kwd_attrs=["True"],
2305 kwd_patterns=[pattern_1],
2306 ),
2307 ast.MatchSequence([ast.MatchStar("True")]),
2308 ast.MatchAs(name="False"),
2309 ast.MatchOr([]),
2310 ast.MatchOr([pattern_1]),
2311 ast.MatchOr([pattern_1, pattern_x, ast.MatchSingleton("xxx")]),
2312 ast.MatchAs(name="_"),
2313 ast.MatchStar(name="x"),
2314 ast.MatchSequence([ast.MatchStar("_")]),
2315 ast.MatchMapping([], [], rest="_"),
2316 ]
2317
2318 def test_match_validation_pattern(self):
2319 name_x = ast.Name("x", ast.Load())
2320 for pattern in self._MATCH_PATTERNS:
2321 with self.subTest(ast.dump(pattern, indent=4)):
2322 node = ast.Match(
2323 subject=name_x,
2324 cases=[ast.match_case(pattern=pattern, body=[ast.Pass()])],
2325 )
2326 node = ast.fix_missing_locations(node)
2327 module = ast.Module([node], [])
2328 with self.assertRaises(ValueError):
2329 compile(module, "<test>", "exec")
2330
2331
2332 class ConstantTests(unittest.TestCase):
2333 """Tests on the ast.Constant node type."""
2334
2335 def compile_constant(self, value):
2336 tree = ast.parse("x = 123")
2337
2338 node = tree.body[0].value
2339 new_node = ast.Constant(value=value)
2340 ast.copy_location(new_node, node)
2341 tree.body[0].value = new_node
2342
2343 code = compile(tree, "<string>", "exec")
2344
2345 ns = {}
2346 exec(code, ns)
2347 return ns["x"]
2348
2349 def test_validation(self):
2350 with self.assertRaises(TypeError) as cm:
2351 self.compile_constant([1, 2, 3])
2352 self.assertEqual(str(cm.exception), "got an invalid type in Constant: list")
2353
2354 def test_singletons(self):
2355 for const in (None, False, True, Ellipsis, b"", frozenset()):
2356 with self.subTest(const=const):
2357 value = self.compile_constant(const)
2358 self.assertIs(value, const)
2359
2360 def test_values(self):
2361 nested_tuple = (1,)
2362 nested_frozenset = frozenset({1})
2363 for level in range(3):
2364 nested_tuple = (nested_tuple, 2)
2365 nested_frozenset = frozenset({nested_frozenset, 2})
2366 values = (
2367 123,
2368 123.0,
2369 123j,
2370 "unicode",
2371 b"bytes",
2372 tuple("tuple"),
2373 frozenset("frozenset"),
2374 nested_tuple,
2375 nested_frozenset,
2376 )
2377 for value in values:
2378 with self.subTest(value=value):
2379 result = self.compile_constant(value)
2380 self.assertEqual(result, value)
2381
2382 def test_assign_to_constant(self):
2383 tree = ast.parse("x = 1")
2384
2385 target = tree.body[0].targets[0]
2386 new_target = ast.Constant(value=1)
2387 ast.copy_location(new_target, target)
2388 tree.body[0].targets[0] = new_target
2389
2390 with self.assertRaises(ValueError) as cm:
2391 compile(tree, "string", "exec")
2392 self.assertEqual(
2393 str(cm.exception),
2394 "expression which can't be assigned " "to in Store context",
2395 )
2396
2397 def test_get_docstring(self):
2398 tree = ast.parse("'docstring'\nx = 1")
2399 self.assertEqual(ast.get_docstring(tree), "docstring")
2400
2401 def get_load_const(self, tree):
2402 # Compile to bytecode, disassemble and get parameter of LOAD_CONST
2403 # instructions
2404 co = compile(tree, "<string>", "exec")
2405 consts = []
2406 for instr in dis.get_instructions(co):
2407 if instr.opname == "LOAD_CONST" or instr.opname == "RETURN_CONST":
2408 consts.append(instr.argval)
2409 return consts
2410
2411 @support.cpython_only
2412 def test_load_const(self):
2413 consts = [None, True, False, 124, 2.0, 3j, "unicode", b"bytes", (1, 2, 3)]
2414
2415 code = "\n".join(["x={!r}".format(const) for const in consts])
2416 code += "\nx = ..."
2417 consts.extend((Ellipsis, None))
2418
2419 tree = ast.parse(code)
2420 self.assertEqual(self.get_load_const(tree), consts)
2421
2422 # Replace expression nodes with constants
2423 for assign, const in zip(tree.body, consts):
2424 assert isinstance(assign, ast.Assign), ast.dump(assign)
2425 new_node = ast.Constant(value=const)
2426 ast.copy_location(new_node, assign.value)
2427 assign.value = new_node
2428
2429 self.assertEqual(self.get_load_const(tree), consts)
2430
2431 def test_literal_eval(self):
2432 tree = ast.parse("1 + 2")
2433 binop = tree.body[0].value
2434
2435 new_left = ast.Constant(value=10)
2436 ast.copy_location(new_left, binop.left)
2437 binop.left = new_left
2438
2439 new_right = ast.Constant(value=20j)
2440 ast.copy_location(new_right, binop.right)
2441 binop.right = new_right
2442
2443 self.assertEqual(ast.literal_eval(binop), 10 + 20j)
2444
2445 def test_string_kind(self):
2446 c = ast.parse('"x"', mode="eval").body
2447 self.assertEqual(c.value, "x")
2448 self.assertEqual(c.kind, None)
2449
2450 c = ast.parse('u"x"', mode="eval").body
2451 self.assertEqual(c.value, "x")
2452 self.assertEqual(c.kind, "u")
2453
2454 c = ast.parse('r"x"', mode="eval").body
2455 self.assertEqual(c.value, "x")
2456 self.assertEqual(c.kind, None)
2457
2458 c = ast.parse('b"x"', mode="eval").body
2459 self.assertEqual(c.value, b"x")
2460 self.assertEqual(c.kind, None)
2461
2462
2463 class EndPositionTests(unittest.TestCase):
2464 """Tests for end position of AST nodes.
2465
2466 Testing end positions of nodes requires a bit of extra care
2467 because of how LL parsers work.
2468 """
2469
2470 def _check_end_pos(self, ast_node, end_lineno, end_col_offset):
2471 self.assertEqual(ast_node.end_lineno, end_lineno)
2472 self.assertEqual(ast_node.end_col_offset, end_col_offset)
2473
2474 def _check_content(self, source, ast_node, content):
2475 self.assertEqual(ast.get_source_segment(source, ast_node), content)
2476
2477 def _parse_value(self, s):
2478 # Use duck-typing to support both single expression
2479 # and a right hand side of an assignment statement.
2480 return ast.parse(s).body[0].value
2481
2482 def test_lambda(self):
2483 s = "lambda x, *y: None"
2484 lam = self._parse_value(s)
2485 self._check_content(s, lam.body, "None")
2486 self._check_content(s, lam.args.args[0], "x")
2487 self._check_content(s, lam.args.vararg, "y")
2488
2489 def test_func_def(self):
2490 s = dedent("""
2491 def func(x: int,
2492 *args: str,
2493 z: float = 0,
2494 **kwargs: Any) -> bool:
2495 return True
2496 """).strip()
2497 fdef = ast.parse(s).body[0]
2498 self._check_end_pos(fdef, 5, 15)
2499 self._check_content(s, fdef.body[0], "return True")
2500 self._check_content(s, fdef.args.args[0], "x: int")
2501 self._check_content(s, fdef.args.args[0].annotation, "int")
2502 self._check_content(s, fdef.args.kwarg, "kwargs: Any")
2503 self._check_content(s, fdef.args.kwarg.annotation, "Any")
2504
2505 def test_call(self):
2506 s = "func(x, y=2, **kw)"
2507 call = self._parse_value(s)
2508 self._check_content(s, call.func, "func")
2509 self._check_content(s, call.keywords[0].value, "2")
2510 self._check_content(s, call.keywords[1].value, "kw")
2511
2512 def test_call_noargs(self):
2513 s = "x[0]()"
2514 call = self._parse_value(s)
2515 self._check_content(s, call.func, "x[0]")
2516 self._check_end_pos(call, 1, 6)
2517
2518 def test_class_def(self):
2519 s = dedent("""
2520 class C(A, B):
2521 x: int = 0
2522 """).strip()
2523 cdef = ast.parse(s).body[0]
2524 self._check_end_pos(cdef, 2, 14)
2525 self._check_content(s, cdef.bases[1], "B")
2526 self._check_content(s, cdef.body[0], "x: int = 0")
2527
2528 def test_class_kw(self):
2529 s = "class S(metaclass=abc.ABCMeta): pass"
2530 cdef = ast.parse(s).body[0]
2531 self._check_content(s, cdef.keywords[0].value, "abc.ABCMeta")
2532
2533 def test_multi_line_str(self):
2534 s = dedent('''
2535 x = """Some multi-line text.
2536
2537 It goes on starting from same indent."""
2538 ''').strip()
2539 assign = ast.parse(s).body[0]
2540 self._check_end_pos(assign, 3, 40)
2541 self._check_end_pos(assign.value, 3, 40)
2542
2543 def test_continued_str(self):
2544 s = dedent("""
2545 x = "first part" \\
2546 "second part"
2547 """).strip()
2548 assign = ast.parse(s).body[0]
2549 self._check_end_pos(assign, 2, 13)
2550 self._check_end_pos(assign.value, 2, 13)
2551
2552 def test_suites(self):
2553 # We intentionally put these into the same string to check
2554 # that empty lines are not part of the suite.
2555 s = dedent("""
2556 while True:
2557 pass
2558
2559 if one():
2560 x = None
2561 elif other():
2562 y = None
2563 else:
2564 z = None
2565
2566 for x, y in stuff:
2567 assert True
2568
2569 try:
2570 raise RuntimeError
2571 except TypeError as e:
2572 pass
2573
2574 pass
2575 """).strip()
2576 mod = ast.parse(s)
2577 while_loop = mod.body[0]
2578 if_stmt = mod.body[1]
2579 for_loop = mod.body[2]
2580 try_stmt = mod.body[3]
2581 pass_stmt = mod.body[4]
2582
2583 self._check_end_pos(while_loop, 2, 8)
2584 self._check_end_pos(if_stmt, 9, 12)
2585 self._check_end_pos(for_loop, 12, 15)
2586 self._check_end_pos(try_stmt, 17, 8)
2587 self._check_end_pos(pass_stmt, 19, 4)
2588
2589 self._check_content(s, while_loop.test, "True")
2590 self._check_content(s, if_stmt.body[0], "x = None")
2591 self._check_content(s, if_stmt.orelse[0].test, "other()")
2592 self._check_content(s, for_loop.target, "x, y")
2593 self._check_content(s, try_stmt.body[0], "raise RuntimeError")
2594 self._check_content(s, try_stmt.handlers[0].type, "TypeError")
2595
2596 def test_fstring(self):
2597 s = 'x = f"abc {x + y} abc"'
2598 fstr = self._parse_value(s)
2599 binop = fstr.values[1].value
2600 self._check_content(s, binop, "x + y")
2601
2602 def test_fstring_multi_line(self):
2603 s = dedent('''
2604 f"""Some multi-line text.
2605 {
2606 arg_one
2607 +
2608 arg_two
2609 }
2610 It goes on..."""
2611 ''').strip()
2612 fstr = self._parse_value(s)
2613 binop = fstr.values[1].value
2614 self._check_end_pos(binop, 5, 7)
2615 self._check_content(s, binop.left, "arg_one")
2616 self._check_content(s, binop.right, "arg_two")
2617
2618 def test_import_from_multi_line(self):
2619 s = dedent("""
2620 from x.y.z import (
2621 a, b, c as c
2622 )
2623 """).strip()
2624 imp = ast.parse(s).body[0]
2625 self._check_end_pos(imp, 3, 1)
2626 self._check_end_pos(imp.names[2], 2, 16)
2627
2628 def test_slices(self):
2629 s1 = "f()[1, 2] [0]"
2630 s2 = "x[ a.b: c.d]"
2631 sm = dedent("""
2632 x[ a.b: f () ,
2633 g () : c.d
2634 ]
2635 """).strip()
2636 i1, i2, im = map(self._parse_value, (s1, s2, sm))
2637 self._check_content(s1, i1.value, "f()[1, 2]")
2638 self._check_content(s1, i1.value.slice, "1, 2")
2639 self._check_content(s2, i2.slice.lower, "a.b")
2640 self._check_content(s2, i2.slice.upper, "c.d")
2641 self._check_content(sm, im.slice.elts[0].upper, "f ()")
2642 self._check_content(sm, im.slice.elts[1].lower, "g ()")
2643 self._check_end_pos(im, 3, 3)
2644
2645 def test_binop(self):
2646 s = dedent("""
2647 (1 * 2 + (3 ) +
2648 4
2649 )
2650 """).strip()
2651 binop = self._parse_value(s)
2652 self._check_end_pos(binop, 2, 6)
2653 self._check_content(s, binop.right, "4")
2654 self._check_content(s, binop.left, "1 * 2 + (3 )")
2655 self._check_content(s, binop.left.right, "3")
2656
2657 def test_boolop(self):
2658 s = dedent("""
2659 if (one_condition and
2660 (other_condition or yet_another_one)):
2661 pass
2662 """).strip()
2663 bop = ast.parse(s).body[0].test
2664 self._check_end_pos(bop, 2, 44)
2665 self._check_content(s, bop.values[1], "other_condition or yet_another_one")
2666
2667 def test_tuples(self):
2668 s1 = "x = () ;"
2669 s2 = "x = 1 , ;"
2670 s3 = "x = (1 , 2 ) ;"
2671 sm = dedent("""
2672 x = (
2673 a, b,
2674 )
2675 """).strip()
2676 t1, t2, t3, tm = map(self._parse_value, (s1, s2, s3, sm))
2677 self._check_content(s1, t1, "()")
2678 self._check_content(s2, t2, "1 ,")
2679 self._check_content(s3, t3, "(1 , 2 )")
2680 self._check_end_pos(tm, 3, 1)
2681
2682 def test_attribute_spaces(self):
2683 s = "func(x. y .z)"
2684 call = self._parse_value(s)
2685 self._check_content(s, call, s)
2686 self._check_content(s, call.args[0], "x. y .z")
2687
2688 def test_redundant_parenthesis(self):
2689 s = "( ( ( a + b ) ) )"
2690 v = ast.parse(s).body[0].value
2691 self.assertEqual(type(v).__name__, "BinOp")
2692 self._check_content(s, v, "a + b")
2693 s2 = "await " + s
2694 v = ast.parse(s2).body[0].value.value
2695 self.assertEqual(type(v).__name__, "BinOp")
2696 self._check_content(s2, v, "a + b")
2697
2698 def test_trailers_with_redundant_parenthesis(self):
2699 tests = (
2700 ("( ( ( a ) ) ) ( )", "Call"),
2701 ("( ( ( a ) ) ) ( b )", "Call"),
2702 ("( ( ( a ) ) ) [ b ]", "Subscript"),
2703 ("( ( ( a ) ) ) . b", "Attribute"),
2704 )
2705 for s, t in tests:
2706 with self.subTest(s):
2707 v = ast.parse(s).body[0].value
2708 self.assertEqual(type(v).__name__, t)
2709 self._check_content(s, v, s)
2710 s2 = "await " + s
2711 v = ast.parse(s2).body[0].value.value
2712 self.assertEqual(type(v).__name__, t)
2713 self._check_content(s2, v, s)
2714
2715 def test_displays(self):
2716 s1 = "[{}, {1, }, {1, 2,} ]"
2717 s2 = "{a: b, f (): g () ,}"
2718 c1 = self._parse_value(s1)
2719 c2 = self._parse_value(s2)
2720 self._check_content(s1, c1.elts[0], "{}")
2721 self._check_content(s1, c1.elts[1], "{1, }")
2722 self._check_content(s1, c1.elts[2], "{1, 2,}")
2723 self._check_content(s2, c2.keys[1], "f ()")
2724 self._check_content(s2, c2.values[1], "g ()")
2725
2726 def test_comprehensions(self):
2727 s = dedent("""
2728 x = [{x for x, y in stuff
2729 if cond.x} for stuff in things]
2730 """).strip()
2731 cmp = self._parse_value(s)
2732 self._check_end_pos(cmp, 2, 37)
2733 self._check_content(s, cmp.generators[0].iter, "things")
2734 self._check_content(s, cmp.elt.generators[0].iter, "stuff")
2735 self._check_content(s, cmp.elt.generators[0].ifs[0], "cond.x")
2736 self._check_content(s, cmp.elt.generators[0].target, "x, y")
2737
2738 def test_yield_await(self):
2739 s = dedent("""
2740 async def f():
2741 yield x
2742 await y
2743 """).strip()
2744 fdef = ast.parse(s).body[0]
2745 self._check_content(s, fdef.body[0].value, "yield x")
2746 self._check_content(s, fdef.body[1].value, "await y")
2747
2748 def test_source_segment_multi(self):
2749 s_orig = dedent("""
2750 x = (
2751 a, b,
2752 ) + ()
2753 """).strip()
2754 s_tuple = dedent("""
2755 (
2756 a, b,
2757 )
2758 """).strip()
2759 binop = self._parse_value(s_orig)
2760 self.assertEqual(ast.get_source_segment(s_orig, binop.left), s_tuple)
2761
2762 def test_source_segment_padded(self):
2763 s_orig = dedent("""
2764 class C:
2765 def fun(self) -> None:
2766 "ЖЖЖЖЖ"
2767 """).strip()
2768 s_method = " def fun(self) -> None:\n" ' "ЖЖЖЖЖ"'
2769 cdef = ast.parse(s_orig).body[0]
2770 self.assertEqual(
2771 ast.get_source_segment(s_orig, cdef.body[0], padded=True), s_method
2772 )
2773
2774 def test_source_segment_endings(self):
2775 s = "v = 1\r\nw = 1\nx = 1\n\ry = 1\rz = 1\r\n"
2776 v, w, x, y, z = ast.parse(s).body
2777 self._check_content(s, v, "v = 1")
2778 self._check_content(s, w, "w = 1")
2779 self._check_content(s, x, "x = 1")
2780 self._check_content(s, y, "y = 1")
2781 self._check_content(s, z, "z = 1")
2782
2783 def test_source_segment_tabs(self):
2784 s = dedent("""
2785 class C:
2786 \t\f def fun(self) -> None:
2787 \t\f pass
2788 """).strip()
2789 s_method = " \t\f def fun(self) -> None:\n" " \t\f pass"
2790
2791 cdef = ast.parse(s).body[0]
2792 self.assertEqual(ast.get_source_segment(s, cdef.body[0], padded=True), s_method)
2793
2794 def test_source_segment_newlines(self):
2795 s = "def f():\n pass\ndef g():\r pass\r\ndef h():\r\n pass\r\n"
2796 f, g, h = ast.parse(s).body
2797 self._check_content(s, f, "def f():\n pass")
2798 self._check_content(s, g, "def g():\r pass")
2799 self._check_content(s, h, "def h():\r\n pass")
2800
2801 s = "def f():\n a = 1\r b = 2\r\n c = 3\n"
2802 f = ast.parse(s).body[0]
2803 self._check_content(s, f, s.rstrip())
2804
2805 def test_source_segment_missing_info(self):
2806 s = "v = 1\r\nw = 1\nx = 1\n\ry = 1\r\n"
2807 v, w, x, y = ast.parse(s).body
2808 del v.lineno
2809 del w.end_lineno
2810 del x.col_offset
2811 del y.end_col_offset
2812 self.assertIsNone(ast.get_source_segment(s, v))
2813 self.assertIsNone(ast.get_source_segment(s, w))
2814 self.assertIsNone(ast.get_source_segment(s, x))
2815 self.assertIsNone(ast.get_source_segment(s, y))
2816
2817
2818 class BaseNodeVisitorCases:
2819 # Both `NodeVisitor` and `NodeTranformer` must raise these warnings:
2820 def test_old_constant_nodes(self):
2821 class Visitor(self.visitor_class):
2822 def visit_Num(self, node):
2823 log.append((node.lineno, "Num", node.n))
2824
2825 def visit_Str(self, node):
2826 log.append((node.lineno, "Str", node.s))
2827
2828 def visit_Bytes(self, node):
2829 log.append((node.lineno, "Bytes", node.s))
2830
2831 def visit_NameConstant(self, node):
2832 log.append((node.lineno, "NameConstant", node.value))
2833
2834 def visit_Ellipsis(self, node):
2835 log.append((node.lineno, "Ellipsis", ...))
2836
2837 mod = ast.parse(
2838 dedent("""\
2839 i = 42
2840 f = 4.25
2841 c = 4.25j
2842 s = 'string'
2843 b = b'bytes'
2844 t = True
2845 n = None
2846 e = ...
2847 """)
2848 )
2849 visitor = Visitor()
2850 log = []
2851 with warnings.catch_warnings(record=True) as wlog:
2852 warnings.filterwarnings("always", "", DeprecationWarning)
2853 visitor.visit(mod)
2854 self.assertEqual(
2855 log,
2856 [
2857 (1, "Num", 42),
2858 (2, "Num", 4.25),
2859 (3, "Num", 4.25j),
2860 (4, "Str", "string"),
2861 (5, "Bytes", b"bytes"),
2862 (6, "NameConstant", True),
2863 (7, "NameConstant", None),
2864 (8, "Ellipsis", ...),
2865 ],
2866 )
2867 self.assertEqual(
2868 [str(w.message) for w in wlog],
2869 [
2870 "visit_Num is deprecated; add visit_Constant",
2871 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
2872 "visit_Num is deprecated; add visit_Constant",
2873 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
2874 "visit_Num is deprecated; add visit_Constant",
2875 "Attribute n is deprecated and will be removed in Python 3.14; use value instead",
2876 "visit_Str is deprecated; add visit_Constant",
2877 "Attribute s is deprecated and will be removed in Python 3.14; use value instead",
2878 "visit_Bytes is deprecated; add visit_Constant",
2879 "Attribute s is deprecated and will be removed in Python 3.14; use value instead",
2880 "visit_NameConstant is deprecated; add visit_Constant",
2881 "visit_NameConstant is deprecated; add visit_Constant",
2882 "visit_Ellipsis is deprecated; add visit_Constant",
2883 ],
2884 )
2885
2886
2887 class NodeVisitorTests(BaseNodeVisitorCases, unittest.TestCase):
2888 visitor_class = ast.NodeVisitor
2889
2890
2891 class NodeTransformerTests(ASTTestMixin, BaseNodeVisitorCases, unittest.TestCase):
2892 visitor_class = ast.NodeTransformer
2893
2894 def assertASTTransformation(self, tranformer_class, initial_code, expected_code):
2895 initial_ast = ast.parse(dedent(initial_code))
2896 expected_ast = ast.parse(dedent(expected_code))
2897
2898 tranformer = tranformer_class()
2899 result_ast = ast.fix_missing_locations(tranformer.visit(initial_ast))
2900
2901 self.assertASTEqual(result_ast, expected_ast)
2902
2903 def test_node_remove_single(self):
2904 code = "def func(arg) -> SomeType: ..."
2905 expected = "def func(arg): ..."
2906
2907 # Since `FunctionDef.returns` is defined as a single value, we test
2908 # the `if isinstance(old_value, AST):` branch here.
2909 class SomeTypeRemover(ast.NodeTransformer):
2910 def visit_Name(self, node: ast.Name):
2911 self.generic_visit(node)
2912 if node.id == "SomeType":
2913 return None
2914 return node
2915
2916 self.assertASTTransformation(SomeTypeRemover, code, expected)
2917
2918 def test_node_remove_from_list(self):
2919 code = """
2920 def func(arg):
2921 print(arg)
2922 yield arg
2923 """
2924 expected = """
2925 def func(arg):
2926 print(arg)
2927 """
2928
2929 # Since `FunctionDef.body` is defined as a list, we test
2930 # the `if isinstance(old_value, list):` branch here.
2931 class YieldRemover(ast.NodeTransformer):
2932 def visit_Expr(self, node: ast.Expr):
2933 self.generic_visit(node)
2934 if isinstance(node.value, ast.Yield):
2935 return None # Remove `yield` from a function
2936 return node
2937
2938 self.assertASTTransformation(YieldRemover, code, expected)
2939
2940 def test_node_return_list(self):
2941 code = """
2942 class DSL(Base, kw1=True): ...
2943 """
2944 expected = """
2945 class DSL(Base, kw1=True, kw2=True, kw3=False): ...
2946 """
2947
2948 class ExtendKeywords(ast.NodeTransformer):
2949 def visit_keyword(self, node: ast.keyword):
2950 self.generic_visit(node)
2951 if node.arg == "kw1":
2952 return [
2953 node,
2954 ast.keyword("kw2", ast.Constant(True)),
2955 ast.keyword("kw3", ast.Constant(False)),
2956 ]
2957 return node
2958
2959 self.assertASTTransformation(ExtendKeywords, code, expected)
2960
2961 def test_node_mutate(self):
2962 code = """
2963 def func(arg):
2964 print(arg)
2965 """
2966 expected = """
2967 def func(arg):
2968 log(arg)
2969 """
2970
2971 class PrintToLog(ast.NodeTransformer):
2972 def visit_Call(self, node: ast.Call):
2973 self.generic_visit(node)
2974 if isinstance(node.func, ast.Name) and node.func.id == "print":
2975 node.func.id = "log"
2976 return node
2977
2978 self.assertASTTransformation(PrintToLog, code, expected)
2979
2980 def test_node_replace(self):
2981 code = """
2982 def func(arg):
2983 print(arg)
2984 """
2985 expected = """
2986 def func(arg):
2987 logger.log(arg, debug=True)
2988 """
2989
2990 class PrintToLog(ast.NodeTransformer):
2991 def visit_Call(self, node: ast.Call):
2992 self.generic_visit(node)
2993 if isinstance(node.func, ast.Name) and node.func.id == "print":
2994 return ast.Call(
2995 func=ast.Attribute(
2996 ast.Name("logger", ctx=ast.Load()),
2997 attr="log",
2998 ctx=ast.Load(),
2999 ),
3000 args=node.args,
3001 keywords=[ast.keyword("debug", ast.Constant(True))],
3002 )
3003 return node
3004
3005 self.assertASTTransformation(PrintToLog, code, expected)
3006
3007
3008 class ASTConstructorTests(unittest.TestCase):
3009 """Test the autogenerated constructors for AST nodes."""
3010
3011 def test_FunctionDef(self):
3012 args = ast.arguments()
3013 self.assertEqual(args.args, [])
3014 self.assertEqual(args.posonlyargs, [])
3015 with self.assertWarnsRegex(
3016 DeprecationWarning,
3017 r"FunctionDef\.__init__ missing 1 required positional argument: 'name'",
3018 ):
3019 node = ast.FunctionDef(args=args)
3020 self.assertFalse(hasattr(node, "name"))
3021 self.assertEqual(node.decorator_list, [])
3022 node = ast.FunctionDef(name="foo", args=args)
3023 self.assertEqual(node.name, "foo")
3024 self.assertEqual(node.decorator_list, [])
3025
3026 def test_expr_context(self):
3027 name = ast.Name("x")
3028 self.assertEqual(name.id, "x")
3029 self.assertIsInstance(name.ctx, ast.Load)
3030
3031 name2 = ast.Name("x", ast.Store())
3032 self.assertEqual(name2.id, "x")
3033 self.assertIsInstance(name2.ctx, ast.Store)
3034
3035 name3 = ast.Name("x", ctx=ast.Del())
3036 self.assertEqual(name3.id, "x")
3037 self.assertIsInstance(name3.ctx, ast.Del)
3038
3039 with self.assertWarnsRegex(
3040 DeprecationWarning,
3041 r"Name\.__init__ missing 1 required positional argument: 'id'",
3042 ):
3043 name3 = ast.Name()
3044
3045 def test_custom_subclass_with_no_fields(self):
3046 class NoInit(ast.AST):
3047 pass
3048
3049 obj = NoInit()
3050 self.assertIsInstance(obj, NoInit)
3051 self.assertEqual(obj.__dict__, {})
3052
3053 def test_fields_but_no_field_types(self):
3054 class Fields(ast.AST):
3055 _fields = ("a",)
3056
3057 obj = Fields()
3058 with self.assertRaises(AttributeError):
3059 obj.a
3060 obj = Fields(a=1)
3061 self.assertEqual(obj.a, 1)
3062
3063 def test_fields_and_types(self):
3064 class FieldsAndTypes(ast.AST):
3065 _fields = ("a",)
3066 _field_types = {"a": int | None}
3067 a: int | None = None
3068
3069 obj = FieldsAndTypes()
3070 self.assertIs(obj.a, None)
3071 obj = FieldsAndTypes(a=1)
3072 self.assertEqual(obj.a, 1)
3073
3074 def test_custom_attributes(self):
3075 class MyAttrs(ast.AST):
3076 _attributes = ("a", "b")
3077
3078 obj = MyAttrs(a=1, b=2)
3079 self.assertEqual(obj.a, 1)
3080 self.assertEqual(obj.b, 2)
3081
3082 with self.assertWarnsRegex(
3083 DeprecationWarning,
3084 r"MyAttrs.__init__ got an unexpected keyword argument 'c'.",
3085 ):
3086 obj = MyAttrs(c=3)
3087
3088 def test_fields_and_types_no_default(self):
3089 class FieldsAndTypesNoDefault(ast.AST):
3090 _fields = ("a",)
3091 _field_types = {"a": int}
3092
3093 with self.assertWarnsRegex(
3094 DeprecationWarning,
3095 r"FieldsAndTypesNoDefault\.__init__ missing 1 required positional argument: 'a'\.",
3096 ):
3097 obj = FieldsAndTypesNoDefault()
3098 with self.assertRaises(AttributeError):
3099 obj.a
3100 obj = FieldsAndTypesNoDefault(a=1)
3101 self.assertEqual(obj.a, 1)
3102
3103 def test_incomplete_field_types(self):
3104 class MoreFieldsThanTypes(ast.AST):
3105 _fields = ("a", "b")
3106 _field_types = {"a": int | None}
3107 a: int | None = None
3108 b: int | None = None
3109
3110 with self.assertWarnsRegex(
3111 DeprecationWarning,
3112 r"Field 'b' is missing from MoreFieldsThanTypes\._field_types",
3113 ):
3114 obj = MoreFieldsThanTypes()
3115 self.assertIs(obj.a, None)
3116 self.assertIs(obj.b, None)
3117
3118 obj = MoreFieldsThanTypes(a=1, b=2)
3119 self.assertEqual(obj.a, 1)
3120 self.assertEqual(obj.b, 2)
3121
3122 def test_malformed_fields_with_bytes(self):
3123 class BadFields(ast.AST):
3124 _fields = (b'\xff'*64,)
3125 _field_types = {'a': int}
3126
3127 # This should not crash
3128 with self.assertWarnsRegex(DeprecationWarning, r"Field b'\\xff\\xff.*' .*"):
3129 obj = BadFields()
3130
3131 def test_complete_field_types(self):
3132 class _AllFieldTypes(ast.AST):
3133 _fields = ("a", "b")
3134 _field_types = {"a": int | None, "b": list[str]}
3135 # This must be set explicitly
3136 a: int | None = None
3137 # This will add an implicit empty list default
3138 b: list[str]
3139
3140 obj = _AllFieldTypes()
3141 self.assertIs(obj.a, None)
3142 self.assertEqual(obj.b, [])
3143
3144 def test_non_str_kwarg(self):
3145 warn_msg = "got an unexpected keyword argument <object object"
3146 with (
3147 self.assertRaises(TypeError),
3148 self.assertWarnsRegex(DeprecationWarning, warn_msg),
3149 ):
3150 ast.Name(**{object(): 'y'})
3151
3152 class FakeStr:
3153 def __init__(self, value):
3154 self.value = value
3155
3156 def __hash__(self):
3157 return hash(self.value)
3158
3159 def __eq__(self, other):
3160 return isinstance(other, str) and self.value == other
3161
3162 with self.assertRaisesRegex(TypeError, "got multiple values for argument"):
3163 ast.Name("x", **{FakeStr('id'): 'y'})
3164
3165
3166 @support.cpython_only
3167 class ModuleStateTests(unittest.TestCase):
3168 # bpo-41194, bpo-41261, bpo-41631: The _ast module uses a global state.
3169
3170 def check_ast_module(self):
3171 # Check that the _ast module still works as expected
3172 code = "x + 1"
3173 filename = "<string>"
3174 mode = "eval"
3175
3176 # Create _ast.AST subclasses instances
3177 ast_tree = compile(code, filename, mode, flags=ast.PyCF_ONLY_AST)
3178
3179 # Call PyAST_Check()
3180 code = compile(ast_tree, filename, mode)
3181 self.assertIsInstance(code, types.CodeType)
3182
3183 def test_reload_module(self):
3184 # bpo-41194: Importing the _ast module twice must not crash.
3185 with support.swap_item(sys.modules, "_ast", None):
3186 del sys.modules["_ast"]
3187 import _ast as ast1
3188
3189 del sys.modules["_ast"]
3190 import _ast as ast2
3191
3192 self.check_ast_module()
3193
3194 # Unloading the two _ast module instances must not crash.
3195 del ast1
3196 del ast2
3197 support.gc_collect()
3198
3199 self.check_ast_module()
3200
3201 def test_sys_modules(self):
3202 # bpo-41631: Test reproducing a Mercurial crash when PyAST_Check()
3203 # imported the _ast module internally.
3204 lazy_mod = object()
3205
3206 def my_import(name, *args, **kw):
3207 sys.modules[name] = lazy_mod
3208 return lazy_mod
3209
3210 with support.swap_item(sys.modules, "_ast", None):
3211 del sys.modules["_ast"]
3212
3213 with support.swap_attr(builtins, "__import__", my_import):
3214 # Test that compile() does not import the _ast module
3215 self.check_ast_module()
3216 self.assertNotIn("_ast", sys.modules)
3217
3218 # Sanity check of the test itself
3219 import _ast
3220
3221 self.assertIs(_ast, lazy_mod)
3222
3223 def test_subinterpreter(self):
3224 # bpo-41631: Importing and using the _ast module in a subinterpreter
3225 # must not crash.
3226 code = dedent("""
3227 import _ast
3228 import ast
3229 import gc
3230 import sys
3231 import types
3232
3233 # Create _ast.AST subclasses instances and call PyAST_Check()
3234 ast_tree = compile('x+1', '<string>', 'eval',
3235 flags=ast.PyCF_ONLY_AST)
3236 code = compile(ast_tree, 'string', 'eval')
3237 if not isinstance(code, types.CodeType):
3238 raise AssertionError
3239
3240 # Unloading the _ast module must not crash.
3241 del ast, _ast
3242 del sys.modules['ast'], sys.modules['_ast']
3243 gc.collect()
3244 """)
3245 res = support.run_in_subinterp(code)
3246 self.assertEqual(res, 0)
3247
3248
3249 class ASTMainTests(unittest.TestCase):
3250 # Tests `ast.main()` function.
3251
3252 def test_cli_file_input(self):
3253 code = "print(1, 2, 3)"
3254 expected = ast.dump(ast.parse(code), indent=3)
3255
3256 with os_helper.temp_dir() as tmp_dir:
3257 filename = os.path.join(tmp_dir, "test_module.py")
3258 with open(filename, "w", encoding="utf-8") as f:
3259 f.write(code)
3260 res, _ = script_helper.run_python_until_end("-m", "ast", filename)
3261
3262 self.assertEqual(res.err, b"")
3263 self.assertEqual(expected.splitlines(), res.out.decode("utf8").splitlines())
3264 self.assertEqual(res.rc, 0)
3265
3266 def compare(left, right):
3267 return ast.dump(left) == ast.dump(right)
3268
3269 class ASTOptimizationTests(unittest.TestCase):
3270 binop = {
3271 "+": ast.Add(),
3272 "-": ast.Sub(),
3273 "*": ast.Mult(),
3274 "/": ast.Div(),
3275 "%": ast.Mod(),
3276 "<<": ast.LShift(),
3277 ">>": ast.RShift(),
3278 "|": ast.BitOr(),
3279 "^": ast.BitXor(),
3280 "&": ast.BitAnd(),
3281 "//": ast.FloorDiv(),
3282 "**": ast.Pow(),
3283 }
3284
3285 unaryop = {
3286 "~": ast.Invert(),
3287 "+": ast.UAdd(),
3288 "-": ast.USub(),
3289 }
3290
3291 def wrap_expr(self, expr):
3292 return ast.Module(body=[ast.Expr(value=expr)])
3293
3294 def wrap_statement(self, statement):
3295 return ast.Module(body=[statement])
3296
3297 def assert_ast(self, code, non_optimized_target, optimized_target):
3298
3299 non_optimized_tree = ast.parse(code, optimize=-1)
3300 optimized_tree = ast.parse(code, optimize=1)
3301
3302 # Is a non-optimized tree equal to a non-optimized target?
3303 self.assertTrue(
3304 compare(non_optimized_tree, non_optimized_target),
3305 f"{ast.dump(non_optimized_target)} must equal "
3306 f"{ast.dump(non_optimized_tree)}",
3307 )
3308
3309 # Is a optimized tree equal to a non-optimized target?
3310 self.assertFalse(
3311 compare(optimized_tree, non_optimized_target),
3312 f"{ast.dump(non_optimized_target)} must not equal "
3313 f"{ast.dump(non_optimized_tree)}"
3314 )
3315
3316 # Is a optimized tree is equal to an optimized target?
3317 self.assertTrue(
3318 compare(optimized_tree, optimized_target),
3319 f"{ast.dump(optimized_target)} must equal "
3320 f"{ast.dump(optimized_tree)}",
3321 )
3322
3323 def create_binop(self, operand, left=ast.Constant(1), right=ast.Constant(1)):
3324 return ast.BinOp(left=left, op=self.binop[operand], right=right)
3325
3326 def test_folding_binop(self):
3327 code = "1 %s 1"
3328 operators = self.binop.keys()
3329
3330 for op in operators:
3331 result_code = code % op
3332 non_optimized_target = self.wrap_expr(self.create_binop(op))
3333 optimized_target = self.wrap_expr(ast.Constant(value=eval(result_code)))
3334
3335 with self.subTest(
3336 result_code=result_code,
3337 non_optimized_target=non_optimized_target,
3338 optimized_target=optimized_target
3339 ):
3340 self.assert_ast(result_code, non_optimized_target, optimized_target)
3341
3342 # Multiplication of constant tuples must be folded
3343 code = "(1,) * 3"
3344 non_optimized_target = self.wrap_expr(self.create_binop("*", ast.Tuple(elts=[ast.Constant(value=1)]), ast.Constant(value=3)))
3345 optimized_target = self.wrap_expr(ast.Constant(eval(code)))
3346
3347 self.assert_ast(code, non_optimized_target, optimized_target)
3348
3349 def test_folding_unaryop(self):
3350 code = "%s1"
3351 operators = self.unaryop.keys()
3352
3353 def create_unaryop(operand):
3354 return ast.UnaryOp(op=self.unaryop[operand], operand=ast.Constant(1))
3355
3356 for op in operators:
3357 result_code = code % op
3358 non_optimized_target = self.wrap_expr(create_unaryop(op))
3359 optimized_target = self.wrap_expr(ast.Constant(eval(result_code)))
3360
3361 with self.subTest(
3362 result_code=result_code,
3363 non_optimized_target=non_optimized_target,
3364 optimized_target=optimized_target
3365 ):
3366 self.assert_ast(result_code, non_optimized_target, optimized_target)
3367
3368 def test_folding_not(self):
3369 code = "not (1 %s (1,))"
3370 operators = {
3371 "in": ast.In(),
3372 "is": ast.Is(),
3373 }
3374 opt_operators = {
3375 "is": ast.IsNot(),
3376 "in": ast.NotIn(),
3377 }
3378
3379 def create_notop(operand):
3380 return ast.UnaryOp(op=ast.Not(), operand=ast.Compare(
3381 left=ast.Constant(value=1),
3382 ops=[operators[operand]],
3383 comparators=[ast.Tuple(elts=[ast.Constant(value=1)])]
3384 ))
3385
3386 for op in operators.keys():
3387 result_code = code % op
3388 non_optimized_target = self.wrap_expr(create_notop(op))
3389 optimized_target = self.wrap_expr(
3390 ast.Compare(left=ast.Constant(1), ops=[opt_operators[op]], comparators=[ast.Constant(value=(1,))])
3391 )
3392
3393 with self.subTest(
3394 result_code=result_code,
3395 non_optimized_target=non_optimized_target,
3396 optimized_target=optimized_target
3397 ):
3398 self.assert_ast(result_code, non_optimized_target, optimized_target)
3399
3400 def test_folding_format(self):
3401 code = "'%s' % (a,)"
3402
3403 non_optimized_target = self.wrap_expr(
3404 ast.BinOp(
3405 left=ast.Constant(value="%s"),
3406 op=ast.Mod(),
3407 right=ast.Tuple(elts=[ast.Name(id='a')]))
3408 )
3409 optimized_target = self.wrap_expr(
3410 ast.JoinedStr(
3411 values=[
3412 ast.FormattedValue(value=ast.Name(id='a'), conversion=115)
3413 ]
3414 )
3415 )
3416
3417 self.assert_ast(code, non_optimized_target, optimized_target)
3418
3419
3420 def test_folding_tuple(self):
3421 code = "(1,)"
3422
3423 non_optimized_target = self.wrap_expr(ast.Tuple(elts=[ast.Constant(1)]))
3424 optimized_target = self.wrap_expr(ast.Constant(value=(1,)))
3425
3426 self.assert_ast(code, non_optimized_target, optimized_target)
3427
3428 def test_folding_comparator(self):
3429 code = "1 %s %s1%s"
3430 operators = [("in", ast.In()), ("not in", ast.NotIn())]
3431 braces = [
3432 ("[", "]", ast.List, (1,)),
3433 ("{", "}", ast.Set, frozenset({1})),
3434 ]
3435 for left, right, non_optimized_comparator, optimized_comparator in braces:
3436 for op, node in operators:
3437 non_optimized_target = self.wrap_expr(ast.Compare(
3438 left=ast.Constant(1), ops=[node],
3439 comparators=[non_optimized_comparator(elts=[ast.Constant(1)])]
3440 ))
3441 optimized_target = self.wrap_expr(ast.Compare(
3442 left=ast.Constant(1), ops=[node],
3443 comparators=[ast.Constant(value=optimized_comparator)]
3444 ))
3445 self.assert_ast(code % (op, left, right), non_optimized_target, optimized_target)
3446
3447 def test_folding_iter(self):
3448 code = "for _ in %s1%s: pass"
3449 braces = [
3450 ("[", "]", ast.List, (1,)),
3451 ("{", "}", ast.Set, frozenset({1})),
3452 ]
3453
3454 for left, right, ast_cls, optimized_iter in braces:
3455 non_optimized_target = self.wrap_statement(ast.For(
3456 target=ast.Name(id="_", ctx=ast.Store()),
3457 iter=ast_cls(elts=[ast.Constant(1)]),
3458 body=[ast.Pass()]
3459 ))
3460 optimized_target = self.wrap_statement(ast.For(
3461 target=ast.Name(id="_", ctx=ast.Store()),
3462 iter=ast.Constant(value=optimized_iter),
3463 body=[ast.Pass()]
3464 ))
3465
3466 self.assert_ast(code % (left, right), non_optimized_target, optimized_target)
3467
3468 def test_folding_subscript(self):
3469 code = "(1,)[0]"
3470
3471 non_optimized_target = self.wrap_expr(
3472 ast.Subscript(value=ast.Tuple(elts=[ast.Constant(value=1)]), slice=ast.Constant(value=0))
3473 )
3474 optimized_target = self.wrap_expr(ast.Constant(value=1))
3475
3476 self.assert_ast(code, non_optimized_target, optimized_target)
3477
3478 def test_folding_type_param_in_function_def(self):
3479 code = "def foo[%s = 1 + 1](): pass"
3480
3481 unoptimized_binop = self.create_binop("+")
3482 unoptimized_type_params = [
3483 ("T", "T", ast.TypeVar),
3484 ("**P", "P", ast.ParamSpec),
3485 ("*Ts", "Ts", ast.TypeVarTuple),
3486 ]
3487
3488 for type, name, type_param in unoptimized_type_params:
3489 result_code = code % type
3490 optimized_target = self.wrap_statement(
3491 ast.FunctionDef(
3492 name='foo',
3493 args=ast.arguments(),
3494 body=[ast.Pass()],
3495 type_params=[type_param(name=name, default_value=ast.Constant(2))]
3496 )
3497 )
3498 non_optimized_target = self.wrap_statement(
3499 ast.FunctionDef(
3500 name='foo',
3501 args=ast.arguments(),
3502 body=[ast.Pass()],
3503 type_params=[type_param(name=name, default_value=unoptimized_binop)]
3504 )
3505 )
3506 self.assert_ast(result_code, non_optimized_target, optimized_target)
3507
3508 def test_folding_type_param_in_class_def(self):
3509 code = "class foo[%s = 1 + 1]: pass"
3510
3511 unoptimized_binop = self.create_binop("+")
3512 unoptimized_type_params = [
3513 ("T", "T", ast.TypeVar),
3514 ("**P", "P", ast.ParamSpec),
3515 ("*Ts", "Ts", ast.TypeVarTuple),
3516 ]
3517
3518 for type, name, type_param in unoptimized_type_params:
3519 result_code = code % type
3520 optimized_target = self.wrap_statement(
3521 ast.ClassDef(
3522 name='foo',
3523 body=[ast.Pass()],
3524 type_params=[type_param(name=name, default_value=ast.Constant(2))]
3525 )
3526 )
3527 non_optimized_target = self.wrap_statement(
3528 ast.ClassDef(
3529 name='foo',
3530 body=[ast.Pass()],
3531 type_params=[type_param(name=name, default_value=unoptimized_binop)]
3532 )
3533 )
3534 self.assert_ast(result_code, non_optimized_target, optimized_target)
3535
3536 def test_folding_type_param_in_type_alias(self):
3537 code = "type foo[%s = 1 + 1] = 1"
3538
3539 unoptimized_binop = self.create_binop("+")
3540 unoptimized_type_params = [
3541 ("T", "T", ast.TypeVar),
3542 ("**P", "P", ast.ParamSpec),
3543 ("*Ts", "Ts", ast.TypeVarTuple),
3544 ]
3545
3546 for type, name, type_param in unoptimized_type_params:
3547 result_code = code % type
3548 optimized_target = self.wrap_statement(
3549 ast.TypeAlias(
3550 name=ast.Name(id='foo', ctx=ast.Store()),
3551 type_params=[type_param(name=name, default_value=ast.Constant(2))],
3552 value=ast.Constant(value=1),
3553 )
3554 )
3555 non_optimized_target = self.wrap_statement(
3556 ast.TypeAlias(
3557 name=ast.Name(id='foo', ctx=ast.Store()),
3558 type_params=[type_param(name=name, default_value=unoptimized_binop)],
3559 value=ast.Constant(value=1),
3560 )
3561 )
3562 self.assert_ast(result_code, non_optimized_target, optimized_target)
3563
3564
3565 if __name__ == "__main__":
3566 unittest.main()