summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fast.html
blob: afc7357520a8fdc3b6d8052a85a5def4bf6fb87a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
 <span id="ast-abstract-syntax-trees"></span><h1>ast — Abstract Syntax Trees</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/ast.py">Lib/ast.py</a></p>  <p>The <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code>ast</code></a> module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.</p> <p>An abstract syntax tree can be generated by passing <a class="reference internal" href="#ast.PyCF_ONLY_AST" title="ast.PyCF_ONLY_AST"><code>ast.PyCF_ONLY_AST</code></a> as a flag to the <a class="reference internal" href="functions#compile" title="compile"><code>compile()</code></a> built-in function, or using the <a class="reference internal" href="#ast.parse" title="ast.parse"><code>parse()</code></a> helper provided in this module. The result will be a tree of objects whose classes all inherit from <a class="reference internal" href="#ast.AST" title="ast.AST"><code>ast.AST</code></a>. An abstract syntax tree can be compiled into a Python code object using the built-in <a class="reference internal" href="functions#compile" title="compile"><code>compile()</code></a> function.</p> <section id="abstract-grammar"> <span id="id1"></span><h2>Abstract Grammar</h2> <p>The abstract grammar is currently defined as follows:</p> <pre data-language="asdl">-- ASDL's 4 builtin types are:
-- identifier, int, string, constant

module Python
{
    mod = Module(stmt* body, type_ignore* type_ignores)
        | Interactive(stmt* body)
        | Expression(expr body)
        | FunctionType(expr* argtypes, expr returns)

    stmt = FunctionDef(identifier name, arguments args,
                       stmt* body, expr* decorator_list, expr? returns,
                       string? type_comment, type_param* type_params)
          | AsyncFunctionDef(identifier name, arguments args,
                             stmt* body, expr* decorator_list, expr? returns,
                             string? type_comment, type_param* type_params)

          | ClassDef(identifier name,
             expr* bases,
             keyword* keywords,
             stmt* body,
             expr* decorator_list,
             type_param* type_params)
          | Return(expr? value)

          | Delete(expr* targets)
          | Assign(expr* targets, expr value, string? type_comment)
          | TypeAlias(expr name, type_param* type_params, expr value)
          | AugAssign(expr target, operator op, expr value)
          -- 'simple' indicates that we annotate simple name without parens
          | AnnAssign(expr target, expr annotation, expr? value, int simple)

          -- use 'orelse' because else is a keyword in target languages
          | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
          | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
          | While(expr test, stmt* body, stmt* orelse)
          | If(expr test, stmt* body, stmt* orelse)
          | With(withitem* items, stmt* body, string? type_comment)
          | AsyncWith(withitem* items, stmt* body, string? type_comment)

          | Match(expr subject, match_case* cases)

          | Raise(expr? exc, expr? cause)
          | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
          | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
          | Assert(expr test, expr? msg)

          | Import(alias* names)
          | ImportFrom(identifier? module, alias* names, int? level)

          | Global(identifier* names)
          | Nonlocal(identifier* names)
          | Expr(expr value)
          | Pass | Break | Continue

          -- col_offset is the byte offset in the utf8 string the parser uses
          attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

          -- BoolOp() can use left &amp; right?
    expr = BoolOp(boolop op, expr* values)
         | NamedExpr(expr target, expr value)
         | BinOp(expr left, operator op, expr right)
         | UnaryOp(unaryop op, expr operand)
         | Lambda(arguments args, expr body)
         | IfExp(expr test, expr body, expr orelse)
         | Dict(expr* keys, expr* values)
         | Set(expr* elts)
         | ListComp(expr elt, comprehension* generators)
         | SetComp(expr elt, comprehension* generators)
         | DictComp(expr key, expr value, comprehension* generators)
         | GeneratorExp(expr elt, comprehension* generators)
         -- the grammar constrains where yield expressions can occur
         | Await(expr value)
         | Yield(expr? value)
         | YieldFrom(expr value)
         -- need sequences for compare to distinguish between
         -- x &lt; 4 &lt; 3 and (x &lt; 4) &lt; 3
         | Compare(expr left, cmpop* ops, expr* comparators)
         | Call(expr func, expr* args, keyword* keywords)
         | FormattedValue(expr value, int conversion, expr? format_spec)
         | JoinedStr(expr* values)
         | Constant(constant value, string? kind)

         -- the following expression can appear in assignment context
         | Attribute(expr value, identifier attr, expr_context ctx)
         | Subscript(expr value, expr slice, expr_context ctx)
         | Starred(expr value, expr_context ctx)
         | Name(identifier id, expr_context ctx)
         | List(expr* elts, expr_context ctx)
         | Tuple(expr* elts, expr_context ctx)

         -- can appear only in Subscript
         | Slice(expr? lower, expr? upper, expr? step)

          -- col_offset is the byte offset in the utf8 string the parser uses
          attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    expr_context = Load | Store | Del

    boolop = And | Or

    operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
                 | RShift | BitOr | BitXor | BitAnd | FloorDiv

    unaryop = Invert | Not | UAdd | USub

    cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn

    comprehension = (expr target, expr iter, expr* ifs, int is_async)

    excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
                    attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,
                 expr* kw_defaults, arg? kwarg, expr* defaults)

    arg = (identifier arg, expr? annotation, string? type_comment)
           attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    -- keyword arguments supplied to call (NULL identifier for **kwargs)
    keyword = (identifier? arg, expr value)
               attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    -- import name with optional 'as' alias.
    alias = (identifier name, identifier? asname)
             attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    withitem = (expr context_expr, expr? optional_vars)

    match_case = (pattern pattern, expr? guard, stmt* body)

    pattern = MatchValue(expr value)
            | MatchSingleton(constant value)
            | MatchSequence(pattern* patterns)
            | MatchMapping(expr* keys, pattern* patterns, identifier? rest)
            | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)

            | MatchStar(identifier? name)
            -- The optional "rest" MatchMapping parameter handles capturing extra mapping keys

            | MatchAs(pattern? pattern, identifier? name)
            | MatchOr(pattern* patterns)

             attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)

    type_ignore = TypeIgnore(int lineno, string tag)

    type_param = TypeVar(identifier name, expr? bound)
               | ParamSpec(identifier name)
               | TypeVarTuple(identifier name)
               attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
}
</pre> </section> <section id="node-classes"> <h2>Node classes</h2> <dl class="py class"> <dt class="sig sig-object py" id="ast.AST">
<code>class ast.AST</code> </dt> <dd>
<p>This is the base of all AST node classes. The actual node classes are derived from the <code>Parser/Python.asdl</code> file, which is reproduced <a class="reference internal" href="#abstract-grammar"><span class="std std-ref">above</span></a>. They are defined in the <code>_ast</code> C module and re-exported in <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code>ast</code></a>.</p> <p>There is one class defined for each left-hand side symbol in the abstract grammar (for example, <code>ast.stmt</code> or <code>ast.expr</code>). In addition, there is one class defined for each constructor on the right-hand side; these classes inherit from the classes for the left-hand side trees. For example, <a class="reference internal" href="#ast.BinOp" title="ast.BinOp"><code>ast.BinOp</code></a> inherits from <code>ast.expr</code>. For production rules with alternatives (aka “sums”), the left-hand side class is abstract: only instances of specific constructor nodes are ever created.</p> <span class="target" id="index-0"></span><span class="target" id="index-1"></span><dl class="py attribute"> <dt class="sig sig-object py" id="ast.AST._fields">
<code>_fields</code> </dt> <dd>
<p>Each concrete class has an attribute <a class="reference internal" href="#ast.AST._fields" title="ast.AST._fields"><code>_fields</code></a> which gives the names of all child nodes.</p> <p>Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example, <a class="reference internal" href="#ast.BinOp" title="ast.BinOp"><code>ast.BinOp</code></a> instances have an attribute <code>left</code> of type <code>ast.expr</code>.</p> <p>If these attributes are marked as optional in the grammar (using a question mark), the value might be <code>None</code>. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST with <a class="reference internal" href="functions#compile" title="compile"><code>compile()</code></a>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ast.AST.lineno">
<code>lineno</code> </dt> <dt class="sig sig-object py" id="ast.AST.col_offset">
<code>col_offset</code> </dt> <dt class="sig sig-object py" id="ast.AST.end_lineno">
<code>end_lineno</code> </dt> <dt class="sig sig-object py" id="ast.AST.end_col_offset">
<code>end_col_offset</code> </dt> <dd>
<p>Instances of <code>ast.expr</code> and <code>ast.stmt</code> subclasses have <a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code>lineno</code></a>, <a class="reference internal" href="#ast.AST.col_offset" title="ast.AST.col_offset"><code>col_offset</code></a>, <a class="reference internal" href="#ast.AST.end_lineno" title="ast.AST.end_lineno"><code>end_lineno</code></a>, and <a class="reference internal" href="#ast.AST.end_col_offset" title="ast.AST.end_col_offset"><code>end_col_offset</code></a> attributes. The <a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code>lineno</code></a> and <a class="reference internal" href="#ast.AST.end_lineno" title="ast.AST.end_lineno"><code>end_lineno</code></a> are the first and last line numbers of source text span (1-indexed so the first line is line 1) and the <a class="reference internal" href="#ast.AST.col_offset" title="ast.AST.col_offset"><code>col_offset</code></a> and <a class="reference internal" href="#ast.AST.end_col_offset" title="ast.AST.end_col_offset"><code>end_col_offset</code></a> are the corresponding UTF-8 byte offsets of the first and last tokens that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.</p> <p>Note that the end positions are not required by the compiler and are therefore optional. The end offset is <em>after</em> the last symbol, for example one can get the source segment of a one-line expression node using <code>source_line[node.col_offset : node.end_col_offset]</code>.</p> </dd>
</dl> <p>The constructor of a class <code>ast.T</code> parses its arguments as follows:</p> <ul class="simple"> <li>If there are positional arguments, there must be as many as there are items in <code>T._fields</code>; they will be assigned as attributes of these names.</li> <li>If there are keyword arguments, they will set the attributes of the same names to the given values.</li> </ul> <p>For example, to create and populate an <a class="reference internal" href="#ast.UnaryOp" title="ast.UnaryOp"><code>ast.UnaryOp</code></a> node, you could use</p> <pre data-language="python">node = ast.UnaryOp()
node.op = ast.USub()
node.operand = ast.Constant()
node.operand.value = 5
node.operand.lineno = 0
node.operand.col_offset = 0
node.lineno = 0
node.col_offset = 0
</pre> <p>or the more compact</p> <pre data-language="python">node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
                   lineno=0, col_offset=0)
</pre> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Class <a class="reference internal" href="#ast.Constant" title="ast.Constant"><code>ast.Constant</code></a> is now used for all constants.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Simple indices are represented by their value, extended slices are represented as tuples.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.8: </span>Old classes <code>ast.Num</code>, <code>ast.Str</code>, <code>ast.Bytes</code>, <code>ast.NameConstant</code> and <code>ast.Ellipsis</code> are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span>Old classes <code>ast.Index</code> and <code>ast.ExtSlice</code> are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The descriptions of the specific node classes displayed here were initially adapted from the fantastic <a class="reference external" href="https://greentreesnakes.readthedocs.io/en/latest/">Green Tree Snakes</a> project and all its contributors.</p> </div> <section id="root-nodes"> <span id="ast-root-nodes"></span><h3>Root nodes</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.Module">
<code>class ast.Module(body, type_ignores)</code> </dt> <dd>
<p>A Python module, as with <a class="reference internal" href="../reference/toplevel_components#file-input"><span class="std std-ref">file input</span></a>. Node type generated by <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a> in the default <code>"exec"</code> <em>mode</em>.</p> <p><em>body</em> is a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> of the module’s <a class="reference internal" href="#ast-statements"><span class="std std-ref">Statements</span></a>.</p> <p><em>type_ignores</em> is a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> of the module’s type ignore comments; see <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a> for more details.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('x = 1'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='x', ctx=Store())],
            value=Constant(value=1))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Expression">
<code>class ast.Expression(body)</code> </dt> <dd>
<p>A single Python <a class="reference internal" href="../reference/toplevel_components#expression-input"><span class="std std-ref">expression input</span></a>. Node type generated by <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a> when <em>mode</em> is <code>"eval"</code>.</p> <p><em>body</em> is a single node, one of the <a class="reference internal" href="#ast-expressions"><span class="std std-ref">expression types</span></a>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
    body=Constant(value=123))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Interactive">
<code>class ast.Interactive(body)</code> </dt> <dd>
<p>A single <a class="reference internal" href="../reference/toplevel_components#interactive"><span class="std std-ref">interactive input</span></a>, like in <a class="reference internal" href="../tutorial/appendix#tut-interac"><span class="std std-ref">Interactive Mode</span></a>. Node type generated by <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a> when <em>mode</em> is <code>"single"</code>.</p> <p><em>body</em> is a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> of <a class="reference internal" href="#ast-statements"><span class="std std-ref">statement nodes</span></a>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))
Interactive(
    body=[
        Assign(
            targets=[
                Name(id='x', ctx=Store())],
            value=Constant(value=1)),
        Assign(
            targets=[
                Name(id='y', ctx=Store())],
            value=Constant(value=2))])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.FunctionType">
<code>class ast.FunctionType(argtypes, returns)</code> </dt> <dd>
<p>A representation of an old-style type comments for functions, as Python versions prior to 3.5 didn’t support <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> annotations. Node type generated by <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a> when <em>mode</em> is <code>"func_type"</code>.</p> <p>Such type comments would look like this:</p> <pre data-language="python">def sum_two_number(a, b):
    # type: (int, int) -&gt; int
    return a + b
</pre> <p><em>argtypes</em> is a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> of <a class="reference internal" href="#ast-expressions"><span class="std std-ref">expression nodes</span></a>.</p> <p><em>returns</em> is a single <a class="reference internal" href="#ast-expressions"><span class="std std-ref">expression node</span></a>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('(int, str) -&gt; List[int]', mode='func_type'), indent=4))
FunctionType(
    argtypes=[
        Name(id='int', ctx=Load()),
        Name(id='str', ctx=Load())],
    returns=Subscript(
        value=Name(id='List', ctx=Load()),
        slice=Name(id='int', ctx=Load()),
        ctx=Load()))
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> </section> <section id="literals"> <h3>Literals</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.Constant">
<code>class ast.Constant(value)</code> </dt> <dd>
<p>A constant value. The <code>value</code> attribute of the <code>Constant</code> literal contains the Python object it represents. The values represented can be simple types such as a number, string or <code>None</code>, but also immutable container types (tuples and frozensets) if all of their elements are constant.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
    body=Constant(value=123))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.FormattedValue">
<code>class ast.FormattedValue(value, conversion, format_spec)</code> </dt> <dd>
<p>Node representing a single formatting field in an f-string. If the string contains a single formatting field and nothing else the node can be isolated otherwise it appears in <a class="reference internal" href="#ast.JoinedStr" title="ast.JoinedStr"><code>JoinedStr</code></a>.</p> <ul class="simple"> <li>
<code>value</code> is any expression node (such as a literal, a variable, or a function call).</li> <li>
<p><code>conversion</code> is an integer:</p> <ul> <li>-1: no formatting</li> <li>115: <code>!s</code> string formatting</li> <li>114: <code>!r</code> repr formatting</li> <li>97: <code>!a</code> ascii formatting</li> </ul> </li> <li>
<code>format_spec</code> is a <a class="reference internal" href="#ast.JoinedStr" title="ast.JoinedStr"><code>JoinedStr</code></a> node representing the formatting of the value, or <code>None</code> if no format was specified. Both <code>conversion</code> and <code>format_spec</code> can be set at the same time.</li> </ul> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.JoinedStr">
<code>class ast.JoinedStr(values)</code> </dt> <dd>
<p>An f-string, comprising a series of <a class="reference internal" href="#ast.FormattedValue" title="ast.FormattedValue"><code>FormattedValue</code></a> and <a class="reference internal" href="#ast.Constant" title="ast.Constant"><code>Constant</code></a> nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4))
Expression(
    body=JoinedStr(
        values=[
            Constant(value='sin('),
            FormattedValue(
                value=Name(id='a', ctx=Load()),
                conversion=-1),
            Constant(value=') is '),
            FormattedValue(
                value=Call(
                    func=Name(id='sin', ctx=Load()),
                    args=[
                        Name(id='a', ctx=Load())],
                    keywords=[]),
                conversion=-1,
                format_spec=JoinedStr(
                    values=[
                        Constant(value='.3')]))]))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.List">
<code>class ast.List(elts, ctx)</code> </dt> <dt class="sig sig-object py" id="ast.Tuple">
<code>class ast.Tuple(elts, ctx)</code> </dt> <dd>
<p>A list or tuple. <code>elts</code> holds a list of nodes representing the elements. <code>ctx</code> is <a class="reference internal" href="#ast.Store" title="ast.Store"><code>Store</code></a> if the container is an assignment target (i.e. <code>(x,y)=something</code>), and <a class="reference internal" href="#ast.Load" title="ast.Load"><code>Load</code></a> otherwise.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
Expression(
    body=List(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))
&gt;&gt;&gt; print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
Expression(
    body=Tuple(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Set">
<code>class ast.Set(elts)</code> </dt> <dd>
<p>A set. <code>elts</code> holds a list of nodes representing the set’s elements.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
Expression(
    body=Set(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)]))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Dict">
<code>class ast.Dict(keys, values)</code> </dt> <dd>
<p>A dictionary. <code>keys</code> and <code>values</code> hold lists of nodes representing the keys and the values respectively, in matching order (what would be returned when calling <code>dictionary.keys()</code> and <code>dictionary.values()</code>).</p> <p>When doing dictionary unpacking using dictionary literals the expression to be expanded goes in the <code>values</code> list, with a <code>None</code> at the corresponding position in <code>keys</code>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4))
Expression(
    body=Dict(
        keys=[
            Constant(value='a'),
            None],
        values=[
            Constant(value=1),
            Name(id='d', ctx=Load())]))
</pre> </dd>
</dl> </section> <section id="variables"> <h3>Variables</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.Name">
<code>class ast.Name(id, ctx)</code> </dt> <dd>
<p>A variable name. <code>id</code> holds the name as a string, and <code>ctx</code> is one of the following types.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Load">
<code>class ast.Load</code> </dt> <dt class="sig sig-object py" id="ast.Store">
<code>class ast.Store</code> </dt> <dt class="sig sig-object py" id="ast.Del">
<code>class ast.Del</code> </dt> <dd>
<p>Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('a'), indent=4))
Module(
    body=[
        Expr(
            value=Name(id='a', ctx=Load()))],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('a = 1'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='a', ctx=Store())],
            value=Constant(value=1))],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('del a'), indent=4))
Module(
    body=[
        Delete(
            targets=[
                Name(id='a', ctx=Del())])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Starred">
<code>class ast.Starred(value, ctx)</code> </dt> <dd>
<p>A <code>*var</code> variable reference. <code>value</code> holds the variable, typically a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> node. This type must be used when building a <a class="reference internal" href="#ast.Call" title="ast.Call"><code>Call</code></a> node with <code>*args</code>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('a, *b = it'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Tuple(
                    elts=[
                        Name(id='a', ctx=Store()),
                        Starred(
                            value=Name(id='b', ctx=Store()),
                            ctx=Store())],
                    ctx=Store())],
            value=Name(id='it', ctx=Load()))],
    type_ignores=[])
</pre> </dd>
</dl> </section> <section id="expressions"> <span id="ast-expressions"></span><h3>Expressions</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.Expr">
<code>class ast.Expr(value)</code> </dt> <dd>
<p>When an expression, such as a function call, appears as a statement by itself with its return value not used or stored, it is wrapped in this container. <code>value</code> holds one of the other nodes in this section, a <a class="reference internal" href="#ast.Constant" title="ast.Constant"><code>Constant</code></a>, a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a>, a <a class="reference internal" href="#ast.Lambda" title="ast.Lambda"><code>Lambda</code></a>, a <a class="reference internal" href="#ast.Yield" title="ast.Yield"><code>Yield</code></a> or <a class="reference internal" href="#ast.YieldFrom" title="ast.YieldFrom"><code>YieldFrom</code></a> node.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('-a'), indent=4))
Module(
    body=[
        Expr(
            value=UnaryOp(
                op=USub(),
                operand=Name(id='a', ctx=Load())))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.UnaryOp">
<code>class ast.UnaryOp(op, operand)</code> </dt> <dd>
<p>A unary operation. <code>op</code> is the operator, and <code>operand</code> any expression node.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.UAdd">
<code>class ast.UAdd</code> </dt> <dt class="sig sig-object py" id="ast.USub">
<code>class ast.USub</code> </dt> <dt class="sig sig-object py" id="ast.Not">
<code>class ast.Not</code> </dt> <dt class="sig sig-object py" id="ast.Invert">
<code>class ast.Invert</code> </dt> <dd>
<p>Unary operator tokens. <a class="reference internal" href="#ast.Not" title="ast.Not"><code>Not</code></a> is the <code>not</code> keyword, <a class="reference internal" href="#ast.Invert" title="ast.Invert"><code>Invert</code></a> is the <code>~</code> operator.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
    body=UnaryOp(
        op=Not(),
        operand=Name(id='x', ctx=Load())))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.BinOp">
<code>class ast.BinOp(left, op, right)</code> </dt> <dd>
<p>A binary operation (like addition or division). <code>op</code> is the operator, and <code>left</code> and <code>right</code> are any expression nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
Expression(
    body=BinOp(
        left=Name(id='x', ctx=Load()),
        op=Add(),
        right=Name(id='y', ctx=Load())))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Add">
<code>class ast.Add</code> </dt> <dt class="sig sig-object py" id="ast.Sub">
<code>class ast.Sub</code> </dt> <dt class="sig sig-object py" id="ast.Mult">
<code>class ast.Mult</code> </dt> <dt class="sig sig-object py" id="ast.Div">
<code>class ast.Div</code> </dt> <dt class="sig sig-object py" id="ast.FloorDiv">
<code>class ast.FloorDiv</code> </dt> <dt class="sig sig-object py" id="ast.Mod">
<code>class ast.Mod</code> </dt> <dt class="sig sig-object py" id="ast.Pow">
<code>class ast.Pow</code> </dt> <dt class="sig sig-object py" id="ast.LShift">
<code>class ast.LShift</code> </dt> <dt class="sig sig-object py" id="ast.RShift">
<code>class ast.RShift</code> </dt> <dt class="sig sig-object py" id="ast.BitOr">
<code>class ast.BitOr</code> </dt> <dt class="sig sig-object py" id="ast.BitXor">
<code>class ast.BitXor</code> </dt> <dt class="sig sig-object py" id="ast.BitAnd">
<code>class ast.BitAnd</code> </dt> <dt class="sig sig-object py" id="ast.MatMult">
<code>class ast.MatMult</code> </dt> <dd>
<p>Binary operator tokens.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.BoolOp">
<code>class ast.BoolOp(op, values)</code> </dt> <dd>
<p>A boolean operation, ‘or’ or ‘and’. <code>op</code> is <a class="reference internal" href="#ast.Or" title="ast.Or"><code>Or</code></a> or <a class="reference internal" href="#ast.And" title="ast.And"><code>And</code></a>. <code>values</code> are the values involved. Consecutive operations with the same operator, such as <code>a or b or c</code>, are collapsed into one node with several values.</p> <p>This doesn’t include <code>not</code>, which is a <a class="reference internal" href="#ast.UnaryOp" title="ast.UnaryOp"><code>UnaryOp</code></a>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
Expression(
    body=BoolOp(
        op=Or(),
        values=[
            Name(id='x', ctx=Load()),
            Name(id='y', ctx=Load())]))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.And">
<code>class ast.And</code> </dt> <dt class="sig sig-object py" id="ast.Or">
<code>class ast.Or</code> </dt> <dd>
<p>Boolean operator tokens.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Compare">
<code>class ast.Compare(left, ops, comparators)</code> </dt> <dd>
<p>A comparison of two or more values. <code>left</code> is the first value in the comparison, <code>ops</code> the list of operators, and <code>comparators</code> the list of values after the first element in the comparison.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('1 &lt;= a &lt; 10', mode='eval'), indent=4))
Expression(
    body=Compare(
        left=Constant(value=1),
        ops=[
            LtE(),
            Lt()],
        comparators=[
            Name(id='a', ctx=Load()),
            Constant(value=10)]))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Eq">
<code>class ast.Eq</code> </dt> <dt class="sig sig-object py" id="ast.NotEq">
<code>class ast.NotEq</code> </dt> <dt class="sig sig-object py" id="ast.Lt">
<code>class ast.Lt</code> </dt> <dt class="sig sig-object py" id="ast.LtE">
<code>class ast.LtE</code> </dt> <dt class="sig sig-object py" id="ast.Gt">
<code>class ast.Gt</code> </dt> <dt class="sig sig-object py" id="ast.GtE">
<code>class ast.GtE</code> </dt> <dt class="sig sig-object py" id="ast.Is">
<code>class ast.Is</code> </dt> <dt class="sig sig-object py" id="ast.IsNot">
<code>class ast.IsNot</code> </dt> <dt class="sig sig-object py" id="ast.In">
<code>class ast.In</code> </dt> <dt class="sig sig-object py" id="ast.NotIn">
<code>class ast.NotIn</code> </dt> <dd>
<p>Comparison operator tokens.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Call">
<code>class ast.Call(func, args, keywords)</code> </dt> <dd>
<p>A function call. <code>func</code> is the function, which will often be a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> or <a class="reference internal" href="#ast.Attribute" title="ast.Attribute"><code>Attribute</code></a> object. Of the arguments:</p> <ul class="simple"> <li>
<code>args</code> holds a list of the arguments passed by position.</li> <li>
<code>keywords</code> holds a list of <a class="reference internal" href="#ast.keyword" title="ast.keyword"><code>keyword</code></a> objects representing arguments passed by keyword.</li> </ul> <p>When creating a <code>Call</code> node, <code>args</code> and <code>keywords</code> are required, but they can be empty lists.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
Expression(
    body=Call(
        func=Name(id='func', ctx=Load()),
        args=[
            Name(id='a', ctx=Load()),
            Starred(
                value=Name(id='d', ctx=Load()),
                ctx=Load())],
        keywords=[
            keyword(
                arg='b',
                value=Name(id='c', ctx=Load())),
            keyword(
                value=Name(id='e', ctx=Load()))]))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.keyword">
<code>class ast.keyword(arg, value)</code> </dt> <dd>
<p>A keyword argument to a function call or class definition. <code>arg</code> is a raw string of the parameter name, <code>value</code> is a node to pass in.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.IfExp">
<code>class ast.IfExp(test, body, orelse)</code> </dt> <dd>
<p>An expression such as <code>a if b else c</code>. Each field holds a single node, so in the following example, all three are <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
Expression(
    body=IfExp(
        test=Name(id='b', ctx=Load()),
        body=Name(id='a', ctx=Load()),
        orelse=Name(id='c', ctx=Load())))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Attribute">
<code>class ast.Attribute(value, attr, ctx)</code> </dt> <dd>
<p>Attribute access, e.g. <code>d.keys</code>. <code>value</code> is a node, typically a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a>. <code>attr</code> is a bare string giving the name of the attribute, and <code>ctx</code> is <a class="reference internal" href="#ast.Load" title="ast.Load"><code>Load</code></a>, <a class="reference internal" href="#ast.Store" title="ast.Store"><code>Store</code></a> or <a class="reference internal" href="#ast.Del" title="ast.Del"><code>Del</code></a> according to how the attribute is acted on.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
Expression(
    body=Attribute(
        value=Name(id='snake', ctx=Load()),
        attr='colour',
        ctx=Load()))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.NamedExpr">
<code>class ast.NamedExpr(target, value)</code> </dt> <dd>
<p>A named expression. This AST node is produced by the assignment expressions operator (also known as the walrus operator). As opposed to the <a class="reference internal" href="#ast.Assign" title="ast.Assign"><code>Assign</code></a> node in which the first argument can be multiple nodes, in this case both <code>target</code> and <code>value</code> must be single nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
Expression(
    body=NamedExpr(
        target=Name(id='x', ctx=Store()),
        value=Constant(value=4)))
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <section id="subscripting"> <h4>Subscripting</h4> <dl class="py class"> <dt class="sig sig-object py" id="ast.Subscript">
<code>class ast.Subscript(value, slice, ctx)</code> </dt> <dd>
<p>A subscript, such as <code>l[1]</code>. <code>value</code> is the subscripted object (usually sequence or mapping). <code>slice</code> is an index, slice or key. It can be a <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a> and contain a <a class="reference internal" href="#ast.Slice" title="ast.Slice"><code>Slice</code></a>. <code>ctx</code> is <a class="reference internal" href="#ast.Load" title="ast.Load"><code>Load</code></a>, <a class="reference internal" href="#ast.Store" title="ast.Store"><code>Store</code></a> or <a class="reference internal" href="#ast.Del" title="ast.Del"><code>Del</code></a> according to the action performed with the subscript.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Tuple(
            elts=[
                Slice(
                    lower=Constant(value=1),
                    upper=Constant(value=2)),
                Constant(value=3)],
            ctx=Load()),
        ctx=Load()))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Slice">
<code>class ast.Slice(lower, upper, step)</code> </dt> <dd>
<p>Regular slicing (on the form <code>lower:upper</code> or <code>lower:upper:step</code>). Can occur only inside the <em>slice</em> field of <a class="reference internal" href="#ast.Subscript" title="ast.Subscript"><code>Subscript</code></a>, either directly or as an element of <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Slice(
            lower=Constant(value=1),
            upper=Constant(value=2)),
        ctx=Load()))
</pre> </dd>
</dl> </section> <section id="comprehensions"> <h4>Comprehensions</h4> <dl class="py class"> <dt class="sig sig-object py" id="ast.ListComp">
<code>class ast.ListComp(elt, generators)</code> </dt> <dt class="sig sig-object py" id="ast.SetComp">
<code>class ast.SetComp(elt, generators)</code> </dt> <dt class="sig sig-object py" id="ast.GeneratorExp">
<code>class ast.GeneratorExp(elt, generators)</code> </dt> <dt class="sig sig-object py" id="ast.DictComp">
<code>class ast.DictComp(key, value, generators)</code> </dt> <dd>
<p>List and set comprehensions, generator expressions, and dictionary comprehensions. <code>elt</code> (or <code>key</code> and <code>value</code>) is a single node representing the part that will be evaluated for each item.</p> <p><code>generators</code> is a list of <a class="reference internal" href="#ast.comprehension" title="ast.comprehension"><code>comprehension</code></a> nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
Expression(
    body=ListComp(
        elt=Name(id='x', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
&gt;&gt;&gt; print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
Expression(
    body=DictComp(
        key=Name(id='x', ctx=Load()),
        value=BinOp(
            left=Name(id='x', ctx=Load()),
            op=Pow(),
            right=Constant(value=2)),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
&gt;&gt;&gt; print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
Expression(
    body=SetComp(
        elt=Name(id='x', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.comprehension">
<code>class ast.comprehension(target, iter, ifs, is_async)</code> </dt> <dd>
<p>One <code>for</code> clause in a comprehension. <code>target</code> is the reference to use for each element - typically a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> or <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a> node. <code>iter</code> is the object to iterate over. <code>ifs</code> is a list of test expressions: each <code>for</code> clause can have multiple <code>ifs</code>.</p> <p><code>is_async</code> indicates a comprehension is asynchronous (using an <code>async for</code> instead of <code>for</code>). The value is an integer (0 or 1).</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
...                indent=4)) # Multiple comprehensions in one.
Expression(
    body=ListComp(
        elt=Call(
            func=Name(id='ord', ctx=Load()),
            args=[
                Name(id='c', ctx=Load())],
            keywords=[]),
        generators=[
            comprehension(
                target=Name(id='line', ctx=Store()),
                iter=Name(id='file', ctx=Load()),
                ifs=[],
                is_async=0),
            comprehension(
                target=Name(id='c', ctx=Store()),
                iter=Name(id='line', ctx=Load()),
                ifs=[],
                is_async=0)]))

&gt;&gt;&gt; print(ast.dump(ast.parse('(n**2 for n in it if n&gt;5 if n&lt;10)', mode='eval'),
...                indent=4)) # generator comprehension
Expression(
    body=GeneratorExp(
        elt=BinOp(
            left=Name(id='n', ctx=Load()),
            op=Pow(),
            right=Constant(value=2)),
        generators=[
            comprehension(
                target=Name(id='n', ctx=Store()),
                iter=Name(id='it', ctx=Load()),
                ifs=[
                    Compare(
                        left=Name(id='n', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=5)]),
                    Compare(
                        left=Name(id='n', ctx=Load()),
                        ops=[
                            Lt()],
                        comparators=[
                            Constant(value=10)])],
                is_async=0)]))

&gt;&gt;&gt; print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
...                indent=4)) # Async comprehension
Expression(
    body=ListComp(
        elt=Name(id='i', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='i', ctx=Store()),
                iter=Name(id='soc', ctx=Load()),
                ifs=[],
                is_async=1)]))
</pre> </dd>
</dl> </section> </section> <section id="statements"> <span id="ast-statements"></span><h3>Statements</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.Assign">
<code>class ast.Assign(targets, value, type_comment)</code> </dt> <dd>
<p>An assignment. <code>targets</code> is a list of nodes, and <code>value</code> is a single node.</p> <p>Multiple nodes in <code>targets</code> represents assigning the same value to each. Unpacking is represented by putting a <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a> or <a class="reference internal" href="#ast.List" title="ast.List"><code>List</code></a> within <code>targets</code>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="ast.Assign.type_comment">
<code>type_comment</code> </dt> <dd>
<p><code>type_comment</code> is an optional string with the type annotation as a comment.</p> </dd>
</dl> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
Module(
    body=[
        Assign(
            targets=[
                Name(id='a', ctx=Store()),
                Name(id='b', ctx=Store())],
            value=Constant(value=1))],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking
Module(
    body=[
        Assign(
            targets=[
                Tuple(
                    elts=[
                        Name(id='a', ctx=Store()),
                        Name(id='b', ctx=Store())],
                    ctx=Store())],
            value=Name(id='c', ctx=Load()))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.AnnAssign">
<code>class ast.AnnAssign(target, annotation, value, simple)</code> </dt> <dd>
<p>An assignment with a type annotation. <code>target</code> is a single node and can be a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a>, a <a class="reference internal" href="#ast.Attribute" title="ast.Attribute"><code>Attribute</code></a> or a <a class="reference internal" href="#ast.Subscript" title="ast.Subscript"><code>Subscript</code></a>. <code>annotation</code> is the annotation, such as a <a class="reference internal" href="#ast.Constant" title="ast.Constant"><code>Constant</code></a> or <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> node. <code>value</code> is a single optional node. <code>simple</code> is a boolean integer set to True for a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> node in <code>target</code> that do not appear in between parenthesis and are hence pure names and not expressions.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('c: int'), indent=4))
Module(
    body=[
        AnnAssign(
            target=Name(id='c', ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            simple=1)],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
Module(
    body=[
        AnnAssign(
            target=Name(id='a', ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            value=Constant(value=1),
            simple=0)],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
Module(
    body=[
        AnnAssign(
            target=Attribute(
                value=Name(id='a', ctx=Load()),
                attr='b',
                ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            simple=0)],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
Module(
    body=[
        AnnAssign(
            target=Subscript(
                value=Name(id='a', ctx=Load()),
                slice=Constant(value=1),
                ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            simple=0)],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.AugAssign">
<code>class ast.AugAssign(target, op, value)</code> </dt> <dd>
<p>Augmented assignment, such as <code>a += 1</code>. In the following example, <code>target</code> is a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> node for <code>x</code> (with the <a class="reference internal" href="#ast.Store" title="ast.Store"><code>Store</code></a> context), <code>op</code> is <a class="reference internal" href="#ast.Add" title="ast.Add"><code>Add</code></a>, and <code>value</code> is a <a class="reference internal" href="#ast.Constant" title="ast.Constant"><code>Constant</code></a> with value for 1.</p> <p>The <code>target</code> attribute cannot be of class <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a> or <a class="reference internal" href="#ast.List" title="ast.List"><code>List</code></a>, unlike the targets of <a class="reference internal" href="#ast.Assign" title="ast.Assign"><code>Assign</code></a>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('x += 2'), indent=4))
Module(
    body=[
        AugAssign(
            target=Name(id='x', ctx=Store()),
            op=Add(),
            value=Constant(value=2))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Raise">
<code>class ast.Raise(exc, cause)</code> </dt> <dd>
<p>A <code>raise</code> statement. <code>exc</code> is the exception object to be raised, normally a <a class="reference internal" href="#ast.Call" title="ast.Call"><code>Call</code></a> or <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a>, or <code>None</code> for a standalone <code>raise</code>. <code>cause</code> is the optional part for <code>y</code> in <code>raise x from y</code>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('raise x from y'), indent=4))
Module(
    body=[
        Raise(
            exc=Name(id='x', ctx=Load()),
            cause=Name(id='y', ctx=Load()))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Assert">
<code>class ast.Assert(test, msg)</code> </dt> <dd>
<p>An assertion. <code>test</code> holds the condition, such as a <a class="reference internal" href="#ast.Compare" title="ast.Compare"><code>Compare</code></a> node. <code>msg</code> holds the failure message.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('assert x,y'), indent=4))
Module(
    body=[
        Assert(
            test=Name(id='x', ctx=Load()),
            msg=Name(id='y', ctx=Load()))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Delete">
<code>class ast.Delete(targets)</code> </dt> <dd>
<p>Represents a <code>del</code> statement. <code>targets</code> is a list of nodes, such as <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a>, <a class="reference internal" href="#ast.Attribute" title="ast.Attribute"><code>Attribute</code></a> or <a class="reference internal" href="#ast.Subscript" title="ast.Subscript"><code>Subscript</code></a> nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('del x,y,z'), indent=4))
Module(
    body=[
        Delete(
            targets=[
                Name(id='x', ctx=Del()),
                Name(id='y', ctx=Del()),
                Name(id='z', ctx=Del())])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Pass">
<code>class ast.Pass</code> </dt> <dd>
<p>A <code>pass</code> statement.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('pass'), indent=4))
Module(
    body=[
        Pass()],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.TypeAlias">
<code>class ast.TypeAlias(name, type_params, value)</code> </dt> <dd>
<p>A <a class="reference internal" href="typing#type-aliases"><span class="std std-ref">type alias</span></a> created through the <a class="reference internal" href="../reference/simple_stmts#type"><code>type</code></a> statement. <code>name</code> is the name of the alias, <code>type_params</code> is a list of <a class="reference internal" href="#ast-type-params"><span class="std std-ref">type parameters</span></a>, and <code>value</code> is the value of the type alias.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('type Alias = int'), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[],
            value=Name(id='int', ctx=Load()))],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <p>Other statements which are only applicable inside functions or loops are described in other sections.</p> <section id="imports"> <h4>Imports</h4> <dl class="py class"> <dt class="sig sig-object py" id="ast.Import">
<code>class ast.Import(names)</code> </dt> <dd>
<p>An import statement. <code>names</code> is a list of <a class="reference internal" href="#ast.alias" title="ast.alias"><code>alias</code></a> nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('import x,y,z'), indent=4))
Module(
    body=[
        Import(
            names=[
                alias(name='x'),
                alias(name='y'),
                alias(name='z')])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.ImportFrom">
<code>class ast.ImportFrom(module, names, level)</code> </dt> <dd>
<p>Represents <code>from x import y</code>. <code>module</code> is a raw string of the ‘from’ name, without any leading dots, or <code>None</code> for statements such as <code>from . import foo</code>. <code>level</code> is an integer holding the level of the relative import (0 means absolute import).</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Module(
    body=[
        ImportFrom(
            module='y',
            names=[
                alias(name='x'),
                alias(name='y'),
                alias(name='z')],
            level=0)],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.alias">
<code>class ast.alias(name, asname)</code> </dt> <dd>
<p>Both parameters are raw strings of the names. <code>asname</code> can be <code>None</code> if the regular name is to be used.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Module(
    body=[
        ImportFrom(
            module='foo.bar',
            names=[
                alias(name='a', asname='b'),
                alias(name='c')],
            level=2)],
    type_ignores=[])
</pre> </dd>
</dl> </section> </section> <section id="control-flow"> <h3>Control flow</h3> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Optional clauses such as <code>else</code> are stored as an empty list if they’re not present.</p> </div> <dl class="py class"> <dt class="sig sig-object py" id="ast.If">
<code>class ast.If(test, body, orelse)</code> </dt> <dd>
<p>An <code>if</code> statement. <code>test</code> holds a single node, such as a <a class="reference internal" href="#ast.Compare" title="ast.Compare"><code>Compare</code></a> node. <code>body</code> and <code>orelse</code> each hold a list of nodes.</p> <p><code>elif</code> clauses don’t have a special representation in the AST, but rather appear as extra <a class="reference internal" href="#ast.If" title="ast.If"><code>If</code></a> nodes within the <code>orelse</code> section of the previous one.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... if x:
...    ...
... elif y:
...    ...
... else:
...    ...
... """), indent=4))
Module(
    body=[
        If(
            test=Name(id='x', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                If(
                    test=Name(id='y', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))],
                    orelse=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.For">
<code>class ast.For(target, iter, body, orelse, type_comment)</code> </dt> <dd>
<p>A <code>for</code> loop. <code>target</code> holds the variable(s) the loop assigns to, as a single <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a>, <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a>, <a class="reference internal" href="#ast.List" title="ast.List"><code>List</code></a>, <a class="reference internal" href="#ast.Attribute" title="ast.Attribute"><code>Attribute</code></a> or <a class="reference internal" href="#ast.Subscript" title="ast.Subscript"><code>Subscript</code></a> node. <code>iter</code> holds the item to be looped over, again as a single node. <code>body</code> and <code>orelse</code> contain lists of nodes to execute. Those in <code>orelse</code> are executed if the loop finishes normally, rather than via a <code>break</code> statement.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="ast.For.type_comment">
<code>type_comment</code> </dt> <dd>
<p><code>type_comment</code> is an optional string with the type annotation as a comment.</p> </dd>
</dl> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... for x in y:
...     ...
... else:
...     ...
... """), indent=4))
Module(
    body=[
        For(
            target=Name(id='x', ctx=Store()),
            iter=Name(id='y', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.While">
<code>class ast.While(test, body, orelse)</code> </dt> <dd>
<p>A <code>while</code> loop. <code>test</code> holds the condition, such as a <a class="reference internal" href="#ast.Compare" title="ast.Compare"><code>Compare</code></a> node.</p> <pre data-language="pycon3">&gt;&gt; print(ast.dump(ast.parse("""
... while x:
...    ...
... else:
...    ...
... """), indent=4))
Module(
    body=[
        While(
            test=Name(id='x', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Break">
<code>class ast.Break</code> </dt> <dt class="sig sig-object py" id="ast.Continue">
<code>class ast.Continue</code> </dt> <dd>
<p>The <code>break</code> and <code>continue</code> statements.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""\
... for a in b:
...     if a &gt; 5:
...         break
...     else:
...         continue
...
... """), indent=4))
Module(
    body=[
        For(
            target=Name(id='a', ctx=Store()),
            iter=Name(id='b', ctx=Load()),
            body=[
                If(
                    test=Compare(
                        left=Name(id='a', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=5)]),
                    body=[
                        Break()],
                    orelse=[
                        Continue()])],
            orelse=[])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Try">
<code>class ast.Try(body, handlers, orelse, finalbody)</code> </dt> <dd>
<p><code>try</code> blocks. All attributes are list of nodes to execute, except for <code>handlers</code>, which is a list of <a class="reference internal" href="#ast.ExceptHandler" title="ast.ExceptHandler"><code>ExceptHandler</code></a> nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... try:
...    ...
... except Exception:
...    ...
... except OtherException as e:
...    ...
... else:
...    ...
... finally:
...    ...
... """), indent=4))
Module(
    body=[
        Try(
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            handlers=[
                ExceptHandler(
                    type=Name(id='Exception', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                ExceptHandler(
                    type=Name(id='OtherException', ctx=Load()),
                    name='e',
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))],
            finalbody=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.TryStar">
<code>class ast.TryStar(body, handlers, orelse, finalbody)</code> </dt> <dd>
<p><code>try</code> blocks which are followed by <code>except*</code> clauses. The attributes are the same as for <a class="reference internal" href="#ast.Try" title="ast.Try"><code>Try</code></a> but the <a class="reference internal" href="#ast.ExceptHandler" title="ast.ExceptHandler"><code>ExceptHandler</code></a> nodes in <code>handlers</code> are interpreted as <code>except*</code> blocks rather then <code>except</code>.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... try:
...    ...
... except* Exception:
...    ...
... """), indent=4))
Module(
    body=[
        TryStar(
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            handlers=[
                ExceptHandler(
                    type=Name(id='Exception', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])],
            orelse=[],
            finalbody=[])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.ExceptHandler">
<code>class ast.ExceptHandler(type, name, body)</code> </dt> <dd>
<p>A single <code>except</code> clause. <code>type</code> is the exception type it will match, typically a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> node (or <code>None</code> for a catch-all <code>except:</code> clause). <code>name</code> is a raw string for the name to hold the exception, or <code>None</code> if the clause doesn’t have <code>as foo</code>. <code>body</code> is a list of nodes.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""\
... try:
...     a + 1
... except TypeError:
...     pass
... """), indent=4))
Module(
    body=[
        Try(
            body=[
                Expr(
                    value=BinOp(
                        left=Name(id='a', ctx=Load()),
                        op=Add(),
                        right=Constant(value=1)))],
            handlers=[
                ExceptHandler(
                    type=Name(id='TypeError', ctx=Load()),
                    body=[
                        Pass()])],
            orelse=[],
            finalbody=[])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.With">
<code>class ast.With(items, body, type_comment)</code> </dt> <dd>
<p>A <code>with</code> block. <code>items</code> is a list of <a class="reference internal" href="#ast.withitem" title="ast.withitem"><code>withitem</code></a> nodes representing the context managers, and <code>body</code> is the indented block inside the context.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="ast.With.type_comment">
<code>type_comment</code> </dt> <dd>
<p><code>type_comment</code> is an optional string with the type annotation as a comment.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.withitem">
<code>class ast.withitem(context_expr, optional_vars)</code> </dt> <dd>
<p>A single context manager in a <code>with</code> block. <code>context_expr</code> is the context manager, often a <a class="reference internal" href="#ast.Call" title="ast.Call"><code>Call</code></a> node. <code>optional_vars</code> is a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a>, <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a> or <a class="reference internal" href="#ast.List" title="ast.List"><code>List</code></a> for the <code>as foo</code> part, or <code>None</code> if that isn’t used.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""\
... with a as b, c as d:
...    something(b, d)
... """), indent=4))
Module(
    body=[
        With(
            items=[
                withitem(
                    context_expr=Name(id='a', ctx=Load()),
                    optional_vars=Name(id='b', ctx=Store())),
                withitem(
                    context_expr=Name(id='c', ctx=Load()),
                    optional_vars=Name(id='d', ctx=Store()))],
            body=[
                Expr(
                    value=Call(
                        func=Name(id='something', ctx=Load()),
                        args=[
                            Name(id='b', ctx=Load()),
                            Name(id='d', ctx=Load())],
                        keywords=[]))])],
    type_ignores=[])
</pre> </dd>
</dl> </section> <section id="pattern-matching"> <h3>Pattern matching</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.Match">
<code>class ast.Match(subject, cases)</code> </dt> <dd>
<p>A <code>match</code> statement. <code>subject</code> holds the subject of the match (the object that is being matched against the cases) and <code>cases</code> contains an iterable of <a class="reference internal" href="#ast.match_case" title="ast.match_case"><code>match_case</code></a> nodes with the different cases.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.match_case">
<code>class ast.match_case(pattern, guard, body)</code> </dt> <dd>
<p>A single case pattern in a <code>match</code> statement. <code>pattern</code> contains the match pattern that the subject will be matched against. Note that the <a class="reference internal" href="#ast.AST" title="ast.AST"><code>AST</code></a> nodes produced for patterns differ from those produced for expressions, even when they share the same syntax.</p> <p>The <code>guard</code> attribute contains an expression that will be evaluated if the pattern matches the subject.</p> <p><code>body</code> contains a list of nodes to execute if the pattern matches and the result of evaluating the guard expression is true.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case [x] if x&gt;0:
...         ...
...     case tuple():
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchAs(name='x')]),
                    guard=Compare(
                        left=Name(id='x', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=0)]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='tuple', ctx=Load()),
                        patterns=[],
                        kwd_attrs=[],
                        kwd_patterns=[]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchValue">
<code>class ast.MatchValue(value)</code> </dt> <dd>
<p>A match literal or value pattern that compares by equality. <code>value</code> is an expression node. Permitted value nodes are restricted as described in the match statement documentation. This pattern succeeds if the match subject is equal to the evaluated value.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case "Relevant":
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchValue(
                        value=Constant(value='Relevant')),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchSingleton">
<code>class ast.MatchSingleton(value)</code> </dt> <dd>
<p>A match literal pattern that compares by identity. <code>value</code> is the singleton to be compared against: <code>None</code>, <code>True</code>, or <code>False</code>. This pattern succeeds if the match subject is the given constant.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case None:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSingleton(value=None),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchSequence">
<code>class ast.MatchSequence(patterns)</code> </dt> <dd>
<p>A match sequence pattern. <code>patterns</code> contains the patterns to be matched against the subject elements if the subject is a sequence. Matches a variable length sequence if one of the subpatterns is a <code>MatchStar</code> node, otherwise matches a fixed length sequence.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case [1, 2]:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchValue(
                                value=Constant(value=1)),
                            MatchValue(
                                value=Constant(value=2))]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchStar">
<code>class ast.MatchStar(name)</code> </dt> <dd>
<p>Matches the rest of the sequence in a variable length match sequence pattern. If <code>name</code> is not <code>None</code>, a list containing the remaining sequence elements is bound to that name if the overall sequence pattern is successful.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case [1, 2, *rest]:
...         ...
...     case [*_]:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchValue(
                                value=Constant(value=1)),
                            MatchValue(
                                value=Constant(value=2)),
                            MatchStar(name='rest')]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchStar()]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchMapping">
<code>class ast.MatchMapping(keys, patterns, rest)</code> </dt> <dd>
<p>A match mapping pattern. <code>keys</code> is a sequence of expression nodes. <code>patterns</code> is a corresponding sequence of pattern nodes. <code>rest</code> is an optional name that can be specified to capture the remaining mapping elements. Permitted key expressions are restricted as described in the match statement documentation.</p> <p>This pattern succeeds if the subject is a mapping, all evaluated key expressions are present in the mapping, and the value corresponding to each key matches the corresponding subpattern. If <code>rest</code> is not <code>None</code>, a dict containing the remaining mapping elements is bound to that name if the overall mapping pattern is successful.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case {1: _, 2: _}:
...         ...
...     case {**rest}:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchMapping(
                        keys=[
                            Constant(value=1),
                            Constant(value=2)],
                        patterns=[
                            MatchAs(),
                            MatchAs()]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchMapping(keys=[], patterns=[], rest='rest'),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchClass">
<code>class ast.MatchClass(cls, patterns, kwd_attrs, kwd_patterns)</code> </dt> <dd>
<p>A match class pattern. <code>cls</code> is an expression giving the nominal class to be matched. <code>patterns</code> is a sequence of pattern nodes to be matched against the class defined sequence of pattern matching attributes. <code>kwd_attrs</code> is a sequence of additional attributes to be matched (specified as keyword arguments in the class pattern), <code>kwd_patterns</code> are the corresponding patterns (specified as keyword values in the class pattern).</p> <p>This pattern succeeds if the subject is an instance of the nominated class, all positional patterns match the corresponding class-defined attributes, and any specified keyword attributes match their corresponding pattern.</p> <p>Note: classes may define a property that returns self in order to match a pattern node against the instance being matched. Several builtin types are also matched that way, as described in the match statement documentation.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case Point2D(0, 0):
...         ...
...     case Point3D(x=0, y=0, z=0):
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='Point2D', ctx=Load()),
                        patterns=[
                            MatchValue(
                                value=Constant(value=0)),
                            MatchValue(
                                value=Constant(value=0))],
                        kwd_attrs=[],
                        kwd_patterns=[]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='Point3D', ctx=Load()),
                        patterns=[],
                        kwd_attrs=[
                            'x',
                            'y',
                            'z'],
                        kwd_patterns=[
                            MatchValue(
                                value=Constant(value=0)),
                            MatchValue(
                                value=Constant(value=0)),
                            MatchValue(
                                value=Constant(value=0))]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchAs">
<code>class ast.MatchAs(pattern, name)</code> </dt> <dd>
<p>A match “as-pattern”, capture pattern or wildcard pattern. <code>pattern</code> contains the match pattern that the subject will be matched against. If the pattern is <code>None</code>, the node represents a capture pattern (i.e a bare name) and will always succeed.</p> <p>The <code>name</code> attribute contains the name that will be bound if the pattern is successful. If <code>name</code> is <code>None</code>, <code>pattern</code> must also be <code>None</code> and the node represents the wildcard pattern.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case [x] as y:
...         ...
...     case _:
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchAs(
                        pattern=MatchSequence(
                            patterns=[
                                MatchAs(name='x')]),
                        name='y'),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchAs(),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.MatchOr">
<code>class ast.MatchOr(patterns)</code> </dt> <dd>
<p>A match “or-pattern”. An or-pattern matches each of its subpatterns in turn to the subject, until one succeeds. The or-pattern is then deemed to succeed. If none of the subpatterns succeed the or-pattern fails. The <code>patterns</code> attribute contains a list of match pattern nodes that will be matched against the subject.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""
... match x:
...     case [x] | (y):
...         ...
... """), indent=4))
Module(
    body=[
        Match(
            subject=Name(id='x', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchOr(
                        patterns=[
                            MatchSequence(
                                patterns=[
                                    MatchAs(name='x')]),
                            MatchAs(name='y')]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> </section> <section id="type-parameters"> <span id="ast-type-params"></span><h3>Type parameters</h3> <p><a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">Type parameters</span></a> can exist on classes, functions, and type aliases.</p> <dl class="py class"> <dt class="sig sig-object py" id="ast.TypeVar">
<code>class ast.TypeVar(name, bound)</code> </dt> <dd>
<p>A <a class="reference internal" href="typing#typing.TypeVar" title="typing.TypeVar"><code>typing.TypeVar</code></a>. <code>name</code> is the name of the type variable. <code>bound</code> is the bound or constraints, if any. If <code>bound</code> is a <a class="reference internal" href="#ast.Tuple" title="ast.Tuple"><code>Tuple</code></a>, it represents constraints; otherwise it represents the bound.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("type Alias[T: int] = list[T]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                TypeVar(
                    name='T',
                    bound=Name(id='int', ctx=Load()))],
            value=Subscript(
                value=Name(id='list', ctx=Load()),
                slice=Name(id='T', ctx=Load()),
                ctx=Load()))],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.ParamSpec">
<code>class ast.ParamSpec(name)</code> </dt> <dd>
<p>A <a class="reference internal" href="typing#typing.ParamSpec" title="typing.ParamSpec"><code>typing.ParamSpec</code></a>. <code>name</code> is the name of the parameter specification.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("type Alias[**P] = Callable[P, int]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                ParamSpec(name='P')],
            value=Subscript(
                value=Name(id='Callable', ctx=Load()),
                slice=Tuple(
                    elts=[
                        Name(id='P', ctx=Load()),
                        Name(id='int', ctx=Load())],
                    ctx=Load()),
                ctx=Load()))],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.TypeVarTuple">
<code>class ast.TypeVarTuple(name)</code> </dt> <dd>
<p>A <a class="reference internal" href="typing#typing.TypeVarTuple" title="typing.TypeVarTuple"><code>typing.TypeVarTuple</code></a>. <code>name</code> is the name of the type variable tuple.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("type Alias[*Ts] = tuple[*Ts]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                TypeVarTuple(name='Ts')],
            value=Subscript(
                value=Name(id='tuple', ctx=Load()),
                slice=Tuple(
                    elts=[
                        Starred(
                            value=Name(id='Ts', ctx=Load()),
                            ctx=Load())],
                    ctx=Load()),
                ctx=Load()))],
    type_ignores=[])
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> </section> <section id="function-and-class-definitions"> <h3>Function and class definitions</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.FunctionDef">
<code>class ast.FunctionDef(name, args, body, decorator_list, returns, type_comment, type_params)</code> </dt> <dd>
<p>A function definition.</p> <ul class="simple"> <li>
<code>name</code> is a raw string of the function name.</li> <li>
<code>args</code> is an <a class="reference internal" href="#ast.arguments" title="ast.arguments"><code>arguments</code></a> node.</li> <li>
<code>body</code> is the list of nodes inside the function.</li> <li>
<code>decorator_list</code> is the list of decorators to be applied, stored outermost first (i.e. the first in the list will be applied last).</li> <li>
<code>returns</code> is the return annotation.</li> <li>
<code>type_params</code> is a list of <a class="reference internal" href="#ast-type-params"><span class="std std-ref">type parameters</span></a>.</li> </ul> <dl class="py attribute"> <dt class="sig sig-object py" id="ast.FunctionDef.type_comment">
<code>type_comment</code> </dt> <dd>
<p><code>type_comment</code> is an optional string with the type annotation as a comment.</p> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added <code>type_params</code>.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Lambda">
<code>class ast.Lambda(args, body)</code> </dt> <dd>
<p><code>lambda</code> is a minimal function definition that can be used inside an expression. Unlike <a class="reference internal" href="#ast.FunctionDef" title="ast.FunctionDef"><code>FunctionDef</code></a>, <code>body</code> holds a single node.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Module(
    body=[
        Expr(
            value=Lambda(
                args=arguments(
                    posonlyargs=[],
                    args=[
                        arg(arg='x'),
                        arg(arg='y')],
                    kwonlyargs=[],
                    kw_defaults=[],
                    defaults=[]),
                body=Constant(value=Ellipsis)))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.arguments">
<code>class ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)</code> </dt> <dd>
<p>The arguments for a function.</p> <ul class="simple"> <li>
<code>posonlyargs</code>, <code>args</code> and <code>kwonlyargs</code> are lists of <a class="reference internal" href="#ast.arg" title="ast.arg"><code>arg</code></a> nodes.</li> <li>
<code>vararg</code> and <code>kwarg</code> are single <a class="reference internal" href="#ast.arg" title="ast.arg"><code>arg</code></a> nodes, referring to the <code>*args, **kwargs</code> parameters.</li> <li>
<code>kw_defaults</code> is a list of default values for keyword-only arguments. If one is <code>None</code>, the corresponding argument is required.</li> <li>
<code>defaults</code> is a list of default values for arguments that can be passed positionally. If there are fewer defaults, they correspond to the last n arguments.</li> </ul> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.arg">
<code>class ast.arg(arg, annotation, type_comment)</code> </dt> <dd>
<p>A single argument in a list. <code>arg</code> is a raw string of the argument name; <code>annotation</code> is its annotation, such as a <a class="reference internal" href="#ast.Name" title="ast.Name"><code>Name</code></a> node.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="ast.arg.type_comment">
<code>type_comment</code> </dt> <dd>
<p><code>type_comment</code> is an optional string with the type annotation as a comment</p> </dd>
</dl> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""\
... @decorator1
... @decorator2
... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -&gt; 'return annotation':
...     pass
... """), indent=4))
Module(
    body=[
        FunctionDef(
            name='f',
            args=arguments(
                posonlyargs=[],
                args=[
                    arg(
                        arg='a',
                        annotation=Constant(value='annotation')),
                    arg(arg='b'),
                    arg(arg='c')],
                vararg=arg(arg='d'),
                kwonlyargs=[
                    arg(arg='e'),
                    arg(arg='f')],
                kw_defaults=[
                    None,
                    Constant(value=3)],
                kwarg=arg(arg='g'),
                defaults=[
                    Constant(value=1),
                    Constant(value=2)]),
            body=[
                Pass()],
            decorator_list=[
                Name(id='decorator1', ctx=Load()),
                Name(id='decorator2', ctx=Load())],
            returns=Constant(value='return annotation'),
            type_params=[])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Return">
<code>class ast.Return(value)</code> </dt> <dd>
<p>A <code>return</code> statement.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('return 4'), indent=4))
Module(
    body=[
        Return(
            value=Constant(value=4))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Yield">
<code>class ast.Yield(value)</code> </dt> <dt class="sig sig-object py" id="ast.YieldFrom">
<code>class ast.YieldFrom(value)</code> </dt> <dd>
<p>A <code>yield</code> or <code>yield from</code> expression. Because these are expressions, they must be wrapped in a <a class="reference internal" href="#ast.Expr" title="ast.Expr"><code>Expr</code></a> node if the value sent back is not used.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('yield x'), indent=4))
Module(
    body=[
        Expr(
            value=Yield(
                value=Name(id='x', ctx=Load())))],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('yield from x'), indent=4))
Module(
    body=[
        Expr(
            value=YieldFrom(
                value=Name(id='x', ctx=Load())))],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Global">
<code>class ast.Global(names)</code> </dt> <dt class="sig sig-object py" id="ast.Nonlocal">
<code>class ast.Nonlocal(names)</code> </dt> <dd>
<p><code>global</code> and <code>nonlocal</code> statements. <code>names</code> is a list of raw strings.</p> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse('global x,y,z'), indent=4))
Module(
    body=[
        Global(
            names=[
                'x',
                'y',
                'z'])],
    type_ignores=[])

&gt;&gt;&gt; print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Module(
    body=[
        Nonlocal(
            names=[
                'x',
                'y',
                'z'])],
    type_ignores=[])
</pre> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.ClassDef">
<code>class ast.ClassDef(name, bases, keywords, body, decorator_list, type_params)</code> </dt> <dd>
<p>A class definition.</p> <ul class="simple"> <li>
<code>name</code> is a raw string for the class name</li> <li>
<code>bases</code> is a list of nodes for explicitly specified base classes.</li> <li>
<code>keywords</code> is a list of <a class="reference internal" href="#ast.keyword" title="ast.keyword"><code>keyword</code></a> nodes, principally for ‘metaclass’. Other keywords will be passed to the metaclass, as per <a class="reference external" href="https://peps.python.org/pep-3115/">PEP-3115</a>.</li> <li>
<code>body</code> is a list of nodes representing the code within the class definition.</li> <li>
<code>decorator_list</code> is a list of nodes, as in <a class="reference internal" href="#ast.FunctionDef" title="ast.FunctionDef"><code>FunctionDef</code></a>.</li> <li>
<code>type_params</code> is a list of <a class="reference internal" href="#ast-type-params"><span class="std std-ref">type parameters</span></a>.</li> </ul> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""\
... @decorator1
... @decorator2
... class Foo(base1, base2, metaclass=meta):
...     pass
... """), indent=4))
Module(
    body=[
        ClassDef(
            name='Foo',
            bases=[
                Name(id='base1', ctx=Load()),
                Name(id='base2', ctx=Load())],
            keywords=[
                keyword(
                    arg='metaclass',
                    value=Name(id='meta', ctx=Load()))],
            body=[
                Pass()],
            decorator_list=[
                Name(id='decorator1', ctx=Load()),
                Name(id='decorator2', ctx=Load())],
            type_params=[])],
    type_ignores=[])
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added <code>type_params</code>.</p> </div> </dd>
</dl> </section> <section id="async-and-await"> <h3>Async and await</h3> <dl class="py class"> <dt class="sig sig-object py" id="ast.AsyncFunctionDef">
<code>class ast.AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment, type_params)</code> </dt> <dd>
<p>An <code>async def</code> function definition. Has the same fields as <a class="reference internal" href="#ast.FunctionDef" title="ast.FunctionDef"><code>FunctionDef</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added <code>type_params</code>.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.Await">
<code>class ast.Await(value)</code> </dt> <dd>
<p>An <code>await</code> expression. <code>value</code> is what it waits for. Only valid in the body of an <a class="reference internal" href="#ast.AsyncFunctionDef" title="ast.AsyncFunctionDef"><code>AsyncFunctionDef</code></a>.</p> </dd>
</dl> <pre data-language="pycon3">&gt;&gt;&gt; print(ast.dump(ast.parse("""\
... async def f():
...     await other_func()
... """), indent=4))
Module(
    body=[
        AsyncFunctionDef(
            name='f',
            args=arguments(
                posonlyargs=[],
                args=[],
                kwonlyargs=[],
                kw_defaults=[],
                defaults=[]),
            body=[
                Expr(
                    value=Await(
                        value=Call(
                            func=Name(id='other_func', ctx=Load()),
                            args=[],
                            keywords=[])))],
            decorator_list=[],
            type_params=[])],
    type_ignores=[])
</pre> <dl class="py class"> <dt class="sig sig-object py" id="ast.AsyncFor">
<code>class ast.AsyncFor(target, iter, body, orelse, type_comment)</code> </dt> <dt class="sig sig-object py" id="ast.AsyncWith">
<code>class ast.AsyncWith(items, body, type_comment)</code> </dt> <dd>
<p><code>async for</code> loops and <code>async with</code> context managers. They have the same fields as <a class="reference internal" href="#ast.For" title="ast.For"><code>For</code></a> and <a class="reference internal" href="#ast.With" title="ast.With"><code>With</code></a>, respectively. Only valid in the body of an <a class="reference internal" href="#ast.AsyncFunctionDef" title="ast.AsyncFunctionDef"><code>AsyncFunctionDef</code></a>.</p> </dd>
</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>When a string is parsed by <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a>, operator nodes (subclasses of <code>ast.operator</code>, <code>ast.unaryop</code>, <code>ast.cmpop</code>, <code>ast.boolop</code> and <code>ast.expr_context</code>) on the returned tree will be singletons. Changes to one will be reflected in all other occurrences of the same value (e.g. <a class="reference internal" href="#ast.Add" title="ast.Add"><code>ast.Add</code></a>).</p> </div> </section> </section> <section id="ast-helpers"> <h2>ast Helpers</h2> <p>Apart from the node classes, the <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code>ast</code></a> module defines these utility functions and classes for traversing abstract syntax trees:</p> <dl class="py function"> <dt class="sig sig-object py" id="ast.parse">
<code>ast.parse(source, filename='&lt;unknown&gt;', mode='exec', *, type_comments=False, feature_version=None)</code> </dt> <dd>
<p>Parse the source into an AST node. Equivalent to <code>compile(source,
filename, mode, ast.PyCF_ONLY_AST)</code>.</p> <p>If <code>type_comments=True</code> is given, the parser is modified to check and return type comments as specified by <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> and <span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a>. This is equivalent to adding <a class="reference internal" href="#ast.PyCF_TYPE_COMMENTS" title="ast.PyCF_TYPE_COMMENTS"><code>ast.PyCF_TYPE_COMMENTS</code></a> to the flags passed to <a class="reference internal" href="functions#compile" title="compile"><code>compile()</code></a>. This will report syntax errors for misplaced type comments. Without this flag, type comments will be ignored, and the <code>type_comment</code> field on selected AST nodes will always be <code>None</code>. In addition, the locations of <code># type:
ignore</code> comments will be returned as the <code>type_ignores</code> attribute of <a class="reference internal" href="#ast.Module" title="ast.Module"><code>Module</code></a> (otherwise it is always an empty list).</p> <p>In addition, if <code>mode</code> is <code>'func_type'</code>, the input syntax is modified to correspond to <span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> “signature type comments”, e.g. <code>(str, int) -&gt; List[str]</code>.</p> <p>Also, setting <code>feature_version</code> to a tuple <code>(major, minor)</code> will attempt to parse using that Python version’s grammar. Currently <code>major</code> must equal to <code>3</code>. For example, setting <code>feature_version=(3, 4)</code> will allow the use of <code>async</code> and <code>await</code> as variable names. The lowest supported version is <code>(3, 4)</code>; the highest is <code>sys.version_info[0:2]</code>.</p> <p>If source contains a null character (’0’), <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Note that successfully parsing source code into an AST object doesn’t guarantee that the source code provided is valid Python code that can be executed as the compilation step can raise further <a class="reference internal" href="exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a> exceptions. For instance, the source <code>return 42</code> generates a valid AST node for a return statement, but it cannot be compiled alone (it needs to be inside a function node).</p> <p>In particular, <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a> won’t do any scoping checks, which the compilation step does.</p> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added <code>type_comments</code>, <code>mode='func_type'</code> and <code>feature_version</code>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.unparse">
<code>ast.unparse(ast_obj)</code> </dt> <dd>
<p>Unparse an <a class="reference internal" href="#ast.AST" title="ast.AST"><code>ast.AST</code></a> object and generate a string with code that would produce an equivalent <a class="reference internal" href="#ast.AST" title="ast.AST"><code>ast.AST</code></a> object if parsed back with <a class="reference internal" href="#ast.parse" title="ast.parse"><code>ast.parse()</code></a>.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>The produced code string will not necessarily be equal to the original code that generated the <a class="reference internal" href="#ast.AST" title="ast.AST"><code>ast.AST</code></a> object (without any compiler optimizations, such as constant tuples/frozensets).</p> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Trying to unparse a highly complex expression would result with <a class="reference internal" href="exceptions#RecursionError" title="RecursionError"><code>RecursionError</code></a>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.literal_eval">
<code>ast.literal_eval(node_or_string)</code> </dt> <dd>
<p>Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, <code>None</code> and <code>Ellipsis</code>.</p> <p>This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.</p> <p>This function had been documented as “safe” in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general <a class="reference internal" href="functions#eval" title="eval"><code>eval()</code></a>. There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>It is possible to crash the Python interpreter due to stack depth limitations in Python’s AST compiler.</p> <p>It can raise <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>, <a class="reference internal" href="exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a>, <a class="reference internal" href="exceptions#MemoryError" title="MemoryError"><code>MemoryError</code></a> and <a class="reference internal" href="exceptions#RecursionError" title="RecursionError"><code>RecursionError</code></a> depending on the malformed input.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Now allows bytes and set literals.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Now supports creating empty sets with <code>'set()'</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>For string inputs, leading spaces and tabs are now stripped.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.get_docstring">
<code>ast.get_docstring(node, clean=True)</code> </dt> <dd>
<p>Return the docstring of the given <em>node</em> (which must be a <a class="reference internal" href="#ast.FunctionDef" title="ast.FunctionDef"><code>FunctionDef</code></a>, <a class="reference internal" href="#ast.AsyncFunctionDef" title="ast.AsyncFunctionDef"><code>AsyncFunctionDef</code></a>, <a class="reference internal" href="#ast.ClassDef" title="ast.ClassDef"><code>ClassDef</code></a>, or <a class="reference internal" href="#ast.Module" title="ast.Module"><code>Module</code></a> node), or <code>None</code> if it has no docstring. If <em>clean</em> is true, clean up the docstring’s indentation with <a class="reference internal" href="inspect#inspect.cleandoc" title="inspect.cleandoc"><code>inspect.cleandoc()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span><a class="reference internal" href="#ast.AsyncFunctionDef" title="ast.AsyncFunctionDef"><code>AsyncFunctionDef</code></a> is now supported.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.get_source_segment">
<code>ast.get_source_segment(source, node, *, padded=False)</code> </dt> <dd>
<p>Get source code segment of the <em>source</em> that generated <em>node</em>. If some location information (<a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code>lineno</code></a>, <a class="reference internal" href="#ast.AST.end_lineno" title="ast.AST.end_lineno"><code>end_lineno</code></a>, <a class="reference internal" href="#ast.AST.col_offset" title="ast.AST.col_offset"><code>col_offset</code></a>, or <a class="reference internal" href="#ast.AST.end_col_offset" title="ast.AST.end_col_offset"><code>end_col_offset</code></a>) is missing, return <code>None</code>.</p> <p>If <em>padded</em> is <code>True</code>, the first line of a multi-line statement will be padded with spaces to match its original position.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.fix_missing_locations">
<code>ast.fix_missing_locations(node)</code> </dt> <dd>
<p>When you compile a node tree with <a class="reference internal" href="functions#compile" title="compile"><code>compile()</code></a>, the compiler expects <a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code>lineno</code></a> and <a class="reference internal" href="#ast.AST.col_offset" title="ast.AST.col_offset"><code>col_offset</code></a> attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at <em>node</em>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.increment_lineno">
<code>ast.increment_lineno(node, n=1)</code> </dt> <dd>
<p>Increment the line number and end line number of each node in the tree starting at <em>node</em> by <em>n</em>. This is useful to “move code” to a different location in a file.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.copy_location">
<code>ast.copy_location(new_node, old_node)</code> </dt> <dd>
<p>Copy source location (<a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code>lineno</code></a>, <a class="reference internal" href="#ast.AST.col_offset" title="ast.AST.col_offset"><code>col_offset</code></a>, <a class="reference internal" href="#ast.AST.end_lineno" title="ast.AST.end_lineno"><code>end_lineno</code></a>, and <a class="reference internal" href="#ast.AST.end_col_offset" title="ast.AST.end_col_offset"><code>end_col_offset</code></a>) from <em>old_node</em> to <em>new_node</em> if possible, and return <em>new_node</em>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.iter_fields">
<code>ast.iter_fields(node)</code> </dt> <dd>
<p>Yield a tuple of <code>(fieldname, value)</code> for each field in <code>node._fields</code> that is present on <em>node</em>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.iter_child_nodes">
<code>ast.iter_child_nodes(node)</code> </dt> <dd>
<p>Yield all direct child nodes of <em>node</em>, that is, all fields that are nodes and all items of fields that are lists of nodes.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.walk">
<code>ast.walk(node)</code> </dt> <dd>
<p>Recursively yield all descendant nodes in the tree starting at <em>node</em> (including <em>node</em> itself), in no specified order. This is useful if you only want to modify nodes in place and don’t care about the context.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.NodeVisitor">
<code>class ast.NodeVisitor</code> </dt> <dd>
<p>A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the <a class="reference internal" href="#ast.NodeVisitor.visit" title="ast.NodeVisitor.visit"><code>visit()</code></a> method.</p> <p>This class is meant to be subclassed, with the subclass adding visitor methods.</p> <dl class="py method"> <dt class="sig sig-object py" id="ast.NodeVisitor.visit">
<code>visit(node)</code> </dt> <dd>
<p>Visit a node. The default implementation calls the method called <code>self.visit_<em>classname</em></code> where <em>classname</em> is the name of the node class, or <a class="reference internal" href="#ast.NodeVisitor.generic_visit" title="ast.NodeVisitor.generic_visit"><code>generic_visit()</code></a> if that method doesn’t exist.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ast.NodeVisitor.generic_visit">
<code>generic_visit(node)</code> </dt> <dd>
<p>This visitor calls <a class="reference internal" href="#ast.NodeVisitor.visit" title="ast.NodeVisitor.visit"><code>visit()</code></a> on all children of the node.</p> <p>Note that child nodes of nodes that have a custom visitor method won’t be visited unless the visitor calls <a class="reference internal" href="#ast.NodeVisitor.generic_visit" title="ast.NodeVisitor.generic_visit"><code>generic_visit()</code></a> or visits them itself.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ast.NodeVisitor.visit_Constant">
<code>visit_Constant(node)</code> </dt> <dd>
<p>Handles all constant nodes.</p> </dd>
</dl> <p>Don’t use the <a class="reference internal" href="#ast.NodeVisitor" title="ast.NodeVisitor"><code>NodeVisitor</code></a> if you want to apply changes to nodes during traversal. For this a special visitor exists (<a class="reference internal" href="#ast.NodeTransformer" title="ast.NodeTransformer"><code>NodeTransformer</code></a>) that allows modifications.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.8: </span>Methods <code>visit_Num()</code>, <code>visit_Str()</code>, <code>visit_Bytes()</code>, <code>visit_NameConstant()</code> and <code>visit_Ellipsis()</code> are deprecated now and will not be called in future Python versions. Add the <a class="reference internal" href="#ast.NodeVisitor.visit_Constant" title="ast.NodeVisitor.visit_Constant"><code>visit_Constant()</code></a> method to handle all constant nodes.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ast.NodeTransformer">
<code>class ast.NodeTransformer</code> </dt> <dd>
<p>A <a class="reference internal" href="#ast.NodeVisitor" title="ast.NodeVisitor"><code>NodeVisitor</code></a> subclass that walks the abstract syntax tree and allows modification of nodes.</p> <p>The <a class="reference internal" href="#ast.NodeTransformer" title="ast.NodeTransformer"><code>NodeTransformer</code></a> will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is <code>None</code>, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place.</p> <p>Here is an example transformer that rewrites all occurrences of name lookups (<code>foo</code>) to <code>data['foo']</code>:</p> <pre data-language="python">class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return Subscript(
            value=Name(id='data', ctx=Load()),
            slice=Constant(value=node.id),
            ctx=node.ctx
        )
</pre> <p>Keep in mind that if the node you’re operating on has child nodes you must either transform the child nodes yourself or call the <a class="reference internal" href="#ast.NodeVisitor.generic_visit" title="ast.NodeVisitor.generic_visit"><code>generic_visit()</code></a> method for the node first.</p> <p>For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node.</p> <p>If <a class="reference internal" href="#ast.NodeTransformer" title="ast.NodeTransformer"><code>NodeTransformer</code></a> introduces new nodes (that weren’t part of original tree) without giving them location information (such as <a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code>lineno</code></a>), <a class="reference internal" href="#ast.fix_missing_locations" title="ast.fix_missing_locations"><code>fix_missing_locations()</code></a> should be called with the new sub-tree to recalculate the location information:</p> <pre data-language="python">tree = ast.parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))
</pre> <p>Usually you use the transformer like this:</p> <pre data-language="python">node = YourTransformer().visit(node)
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ast.dump">
<code>ast.dump(node, annotate_fields=True, include_attributes=False, *, indent=None)</code> </dt> <dd>
<p>Return a formatted dump of the tree in <em>node</em>. This is mainly useful for debugging purposes. If <em>annotate_fields</em> is true (by default), the returned string will show the names and the values for fields. If <em>annotate_fields</em> is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, <em>include_attributes</em> can be set to true.</p> <p>If <em>indent</em> is a non-negative integer or string, then the tree will be pretty-printed with that indent level. An indent level of 0, negative, or <code>""</code> will only insert newlines. <code>None</code> (the default) selects the single line representation. Using a positive integer indent indents that many spaces per level. If <em>indent</em> is a string (such as <code>"\t"</code>), that string is used to indent each level.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>indent</em> option.</p> </div> </dd>
</dl> </section> <section id="compiler-flags"> <span id="ast-compiler-flags"></span><h2>Compiler Flags</h2> <p>The following flags may be passed to <a class="reference internal" href="functions#compile" title="compile"><code>compile()</code></a> in order to change effects on the compilation of a program:</p> <dl class="py data"> <dt class="sig sig-object py" id="ast.PyCF_ALLOW_TOP_LEVEL_AWAIT">
<code>ast.PyCF_ALLOW_TOP_LEVEL_AWAIT</code> </dt> <dd>
<p>Enables support for top-level <code>await</code>, <code>async for</code>, <code>async with</code> and async comprehensions.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ast.PyCF_ONLY_AST">
<code>ast.PyCF_ONLY_AST</code> </dt> <dd>
<p>Generates and returns an abstract syntax tree instead of returning a compiled code object.</p> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ast.PyCF_TYPE_COMMENTS">
<code>ast.PyCF_TYPE_COMMENTS</code> </dt> <dd>
<p>Enables support for <span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> and <span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a> style type comments (<code># type: &lt;type&gt;</code>, <code># type: ignore &lt;stuff&gt;</code>).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> </section> <section id="command-line-usage"> <span id="ast-cli"></span><h2>Command-Line Usage</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> <p>The <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code>ast</code></a> module can be executed as a script from the command line. It is as simple as:</p> <pre data-language="sh">python -m ast [-m &lt;mode&gt;] [-a] [infile]
</pre> <p>The following options are accepted:</p> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-ast-h">
<code>-h, --help</code> </dt> <dd>
<p>Show the help message and exit.</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-ast-m">
<code>-m &lt;mode&gt;</code> </dt> <dt class="sig sig-object std" id="cmdoption-ast-mode">
<code>--mode &lt;mode&gt;</code> </dt> <dd>
<p>Specify what kind of code must be compiled, like the <em>mode</em> argument in <a class="reference internal" href="#ast.parse" title="ast.parse"><code>parse()</code></a>.</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-ast-no-type-comments">
<code>--no-type-comments</code> </dt> <dd>
<p>Don’t parse type comments.</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-ast-a">
<code>-a, --include-attributes</code> </dt> <dd>
<p>Include attributes such as line numbers and column offsets.</p> </dd>
</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-ast-i">
<code>-i &lt;indent&gt;</code> </dt> <dt class="sig sig-object std" id="cmdoption-ast-indent">
<code>--indent &lt;indent&gt;</code> </dt> <dd>
<p>Indentation of nodes in AST (number of spaces).</p> </dd>
</dl> <p>If <code>infile</code> is specified its contents are parsed to AST and dumped to stdout. Otherwise, the content is read from stdin.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://greentreesnakes.readthedocs.io/">Green Tree Snakes</a>, an external documentation resource, has good details on working with Python ASTs.</p> <p><a class="reference external" href="https://asttokens.readthedocs.io/en/latest/user-guide.html">ASTTokens</a> annotates Python ASTs with the positions of tokens and text in the source code that generated them. This is helpful for tools that make source code transformations.</p> <p><a class="reference external" href="https://leoeditor.com/appendices.html#leoast-py">leoAst.py</a> unifies the token-based and parse-tree-based views of python programs by inserting two-way links between tokens and ast nodes.</p> <p><a class="reference external" href="https://libcst.readthedocs.io/">LibCST</a> parses code as a Concrete Syntax Tree that looks like an ast tree and keeps all formatting details. It’s useful for building automated refactoring (codemod) applications and linters.</p> <p><a class="reference external" href="https://parso.readthedocs.io">Parso</a> is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python versions). Parso is also able to list multiple syntax errors in your python file.</p> </div> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/ast.html" class="_attribution-link">https://docs.python.org/3.12/library/ast.html</a>
  </p>
</div>