Python syntax

This Python code:

x + 1

...parses to this syntax tree:

Module
 --.body[0]-->
  Expr
   --.value-->
    BinOp
     --.left-->
      Name { id="x" }
     --.op-->
      Add
     --.right-->
      Constant { v=1, subtype=ConstantInt }

import ast
root = ast.parse(code)

Namex
Constantstr, bytes, int, float, True, False, None...
List[], [x], [x, y]
Tuple(), (x,), (x, y)
Dict{}, { k: v }
ListComp, comprehension[x for y in z if a if b]
GeneratorExp, comprehension(x for y in z if a if b)
Deletedel x["y"]
Attributefoo.bar
Subscriptfoo["bar"], a[:-1]
Slice:, lower:upper:step, lower:upper, lower:, :upper
Assignx = 123, x = y = z = 123
AugAssign, ...BinOp operators...x += 2, x *= 2, x <<= 2
UnaryOpnot x, ~x, +x, -x
Not, Invert, UAdd, USub
BoolOpx and y, x and y and z
And, Or
BinOpx + y, 2**128
Mult, Div, Add, Sub
Mod, Pow, MatMult, FloorDiv
BitAnd, BitOr, BitXor, LShift, RShift
Comparex in arr, x < y <= z == a
Eq, NotEq, Lt, LtE, Gt, GtE
Is, IsNot, In, NotIn
Returnreturn, return x
Breakbreak
Continuecontinue
Passpass
Assertassert x, assert x, msg
Raiseraise NotImplementedError, raise Exception("Foo") from e
IfExpx if y else z
Ifif ... elif ... elif ... else ...
Forfor ..., for ... else ...
Whilewhile ..., while ... else ...
FunctionDef, arguments, argdef f(...): ...
Lambda, arguments, arglambda x: x + 1
ClassDefclass Foo(Bar, Bar2): ...
Call, keywordf(x, foo=456), f(*args, **kwargs)
Import, aliasimport foo, numpy as np
ImportFrom, aliasfrom foo import bar, bar2 as b, from foo import *
Module
Expr
Comment (unofficial)# ...

PythonAST
foo
{"id": "foo", "type": "Name"}
sauté
{"id": "saut\u00e9", "type": "Name"}

Examples...
PythonValue typeAST
Truebool{"type": "Constant", "subtype": "ConstantTrue"}
Falsebool{"type": "Constant", "subtype": "ConstantFalse"}
NoneNoneType{"type": "Constant", "subtype": "ConstantNone"}
123int{"v": 123, "type": "Constant", "subtype": "ConstantInt"}
123_000int{"v": 123000, "type": "Constant", "subtype": "ConstantInt"}
9007199254740993int{"v": "9007199254740993", "type": "Constant", "subtype": "ConstantIntDigits"}
18446744073709551616int{"v": "18446744073709551616", "type": "Constant", "subtype": "ConstantIntDigits"}
0x11 (16 + 1)int{"v": 17, "type": "Constant", "subtype": "ConstantIntHex"}
0b11 (2 + 1)int{"v": 3, "type": "Constant", "subtype": "ConstantIntBinary"}
0o11 (8 + 1)int{"v": 9, "type": "Constant", "subtype": "ConstantIntOctal"}
0.5float{"v": "0.5", "type": "Constant", "subtype": "ConstantFloatDecimal"}
1e6float{"v": "1000000.0", "type": "Constant", "subtype": "ConstantFloatDecimal"}
1e-3float{"v": "0.001", "type": "Constant", "subtype": "ConstantFloatDecimal"}
1.5e6float{"v": "1500000.0", "type": "Constant", "subtype": "ConstantFloatDecimal"}
"123"str{"v": "123", "type": "Constant", "subtype": "ConstantStr"}
"foo\nbar"str{"v": "foo\nbar", "type": "Constant", "subtype": "ConstantStr"}
b"123"bytes{"hex": "313233", "type": "Constant", "subtype": "ConstantBytes"}
b"PK\x03\x04"bytes{"hex": "504b0304", "type": "Constant", "subtype": "ConstantBytes"}

A literal that creates an instance of <class 'list'> with zero or more elements.

PythonAST
[]
{
    "type": "List",
    "elts": []
}
["foo"]
{
    "type": "List",
    "elts": [{"v": "foo", "type": "Constant", "subtype": "ConstantStr"}]
}
["foo", 123, x]
{
    "type": "List",
    "elts": [
        {"v": "foo", "type": "Constant", "subtype": "ConstantStr"},
        {"v": 123, "type": "Constant", "subtype": "ConstantInt"},
        {"id": "x", "type": "Name"}
    ]
}

A literal that creates an instance of <class 'tuple'> with zero or more elements.

PythonAST
()
{
    "type": "Tuple",
    "elts": []
}
(x,)
{
    "type": "Tuple",
    "elts": [{"id": "x", "type": "Name"}]
}
(x, y)
{
    "type": "Tuple",
    "elts": [
        {"id": "x", "type": "Name"},
        {"id": "y", "type": "Name"}
    ]
}
("foo", 123, x)
{
    "type": "Tuple",
    "elts": [
        {"v": "foo", "type": "Constant", "subtype": "ConstantStr"},
        {"v": 123, "type": "Constant", "subtype": "ConstantInt"},
        {"id": "x", "type": "Name"}
    ]
}
x, y = arr
{
    "type": "Assign",
    "targets": [
        {
            "type": "Tuple",
            "elts": [
                {"id": "x", "type": "Name"},
                {"id": "y", "type": "Name"}
            ]
        }
    ],
    "value": {"id": "arr", "type": "Name"}
}
return x, y
{
    "type": "Return",
    "value": {
        "type": "Tuple",
        "elts": [
            {"id": "x", "type": "Name"},
            {"id": "y", "type": "Name"}
        ]
    }
}

A literal that creates an instance of <class 'dict'> with zero or more (key, value) pairs.

PythonAST
{}
{
    "type": "Dict",
    "keys": [],
    "values": []
}
{ "foo": x, 123: y }
{
    "type": "Dict",
    "keys": [
        {"v": "foo", "type": "Constant", "subtype": "ConstantStr"},
        {"v": 123, "type": "Constant", "subtype": "ConstantInt"}
    ],
    "values": [
        {"id": "x", "type": "Name"},
        {"id": "y", "type": "Name"}
    ]
}
{ (1 + 2): "hello" }
{
    "type": "Dict",
    "keys": [
        {
            "type": "BinOp",
            "left": {"v": 1, "type": "Constant", "subtype": "ConstantInt"},
            "op": {"type": "Add"},
            "right": {"v": 2, "type": "Constant", "subtype": "ConstantInt"}
        }
    ],
    "values": [{"v": "hello", "type": "Constant", "subtype": "ConstantStr"}]
}
{ x : y }
{
    "type": "Dict",
    "keys": [{"id": "x", "type": "Name"}],
    "values": [{"id": "y", "type": "Name"}]
}

See ListComp or GeneratorExp

PythonAST
[x for y in z]
{
    "type": "ListComp",
    "elt": {"id": "x", "type": "Name"},
    "generators": [
        {
            "type": "comprehension",
            "target": {"id": "y", "type": "Name"},
            "iter": {"id": "z", "type": "Name"},
            "ifs": []
        }
    ]
}
[x for y in z if a]
{
    "type": "ListComp",
    "elt": {"id": "x", "type": "Name"},
    "generators": [
        {
            "type": "comprehension",
            "target": {"id": "y", "type": "Name"},
            "iter": {"id": "z", "type": "Name"},
            "ifs": [{"id": "a", "type": "Name"}]
        }
    ]
}
[x for y in z if a if b]
{
    "type": "ListComp",
    "elt": {"id": "x", "type": "Name"},
    "generators": [
        {
            "type": "comprehension",
            "target": {"id": "y", "type": "Name"},
            "iter": {"id": "z", "type": "Name"},
            "ifs": [
                {"id": "a", "type": "Name"},
                {"id": "b", "type": "Name"}
            ]
        }
    ]
}

PythonAST
(x for y in z)
{
    "type": "GeneratorExp",
    "elt": {"id": "x", "type": "Name"},
    "generators": [
        {
            "type": "comprehension",
            "target": {"id": "y", "type": "Name"},
            "iter": {"id": "z", "type": "Name"},
            "ifs": []
        }
    ]
}
(x for y in z if a)
{
    "type": "GeneratorExp",
    "elt": {"id": "x", "type": "Name"},
    "generators": [
        {
            "type": "comprehension",
            "target": {"id": "y", "type": "Name"},
            "iter": {"id": "z", "type": "Name"},
            "ifs": [{"id": "a", "type": "Name"}]
        }
    ]
}
(x for y in z if a if b)
{
    "type": "GeneratorExp",
    "elt": {"id": "x", "type": "Name"},
    "generators": [
        {
            "type": "comprehension",
            "target": {"id": "y", "type": "Name"},
            "iter": {"id": "z", "type": "Name"},
            "ifs": [
                {"id": "a", "type": "Name"},
                {"id": "b", "type": "Name"}
            ]
        }
    ]
}

PythonAST
del row["foo"]
{
    "type": "Delete",
    "targets": [
        {
            "type": "Subscript",
            "value": {"id": "row", "type": "Name"},
            "slice": {"v": "foo", "type": "Constant", "subtype": "ConstantStr"}
        }
    ]
}
del foo.bar["item_" + str(i)]
{
    "type": "Delete",
    "targets": [
        {
            "type": "Subscript",
            "value": {
                "type": "Attribute",
                "attr": "bar",
                "value": {"id": "foo", "type": "Name"}
            },
            "slice": {
                "type": "BinOp",
                "left": {"v": "item_", "type": "Constant", "subtype": "ConstantStr"},
                "op": {"type": "Add"},
                "right": {
                    "type": "Call",
                    "func": {"id": "str", "type": "Name"},
                    "args": [{"id": "i", "type": "Name"}],
                    "keywords": []
                }
            }
        }
    ]
}

PythonAST
foo.bar
{
    "type": "Attribute",
    "attr": "bar",
    "value": {"id": "foo", "type": "Name"}
}
(v1 + v2).heading
{
    "type": "Attribute",
    "attr": "heading",
    "value": {
        "type": "BinOp",
        "left": {"id": "v1", "type": "Name"},
        "op": {"type": "Add"},
        "right": {"id": "v2", "type": "Name"}
    }
}

PythonAST
row["foo"]
{
    "type": "Subscript",
    "value": {"id": "row", "type": "Name"},
    "slice": {"v": "foo", "type": "Constant", "subtype": "ConstantStr"}
}
a[0]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {"v": 0, "type": "Constant", "subtype": "ConstantInt"}
}
a[-1]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "UnaryOp",
        "op": {"type": "USub"},
        "operand": {"v": 1, "type": "Constant", "subtype": "ConstantInt"}
    }
}
a[0:2]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": {"v": 0, "type": "Constant", "subtype": "ConstantInt"},
        "upper": {"v": 2, "type": "Constant", "subtype": "ConstantInt"},
        "step": null
    }
}
a[0:2, 5:6]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Tuple",
        "elts": [
            {
                "type": "Slice",
                "lower": {"v": 0, "type": "Constant", "subtype": "ConstantInt"},
                "upper": {"v": 2, "type": "Constant", "subtype": "ConstantInt"},
                "step": null
            },
            {
                "type": "Slice",
                "lower": {"v": 5, "type": "Constant", "subtype": "ConstantInt"},
                "upper": {"v": 6, "type": "Constant", "subtype": "ConstantInt"},
                "step": null
            }
        ]
    }
}

PythonAST
a[lower:upper:step]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": {"id": "lower", "type": "Name"},
        "upper": {"id": "upper", "type": "Name"},
        "step": {"id": "step", "type": "Name"}
    }
}
a[lower:upper]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": {"id": "lower", "type": "Name"},
        "upper": {"id": "upper", "type": "Name"},
        "step": null
    }
}
a[lower:]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": {"id": "lower", "type": "Name"},
        "upper": null,
        "step": null
    }
}
a[:upper]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": null,
        "upper": {"id": "upper", "type": "Name"},
        "step": null
    }
}
a[:]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": null,
        "upper": null,
        "step": null
    }
}
a[0:2]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": {"v": 0, "type": "Constant", "subtype": "ConstantInt"},
        "upper": {"v": 2, "type": "Constant", "subtype": "ConstantInt"},
        "step": null
    }
}
a[0:-1]
{
    "type": "Subscript",
    "value": {"id": "a", "type": "Name"},
    "slice": {
        "type": "Slice",
        "lower": {"v": 0, "type": "Constant", "subtype": "ConstantInt"},
        "upper": {
            "type": "UnaryOp",
            "op": {"type": "USub"},
            "operand": {"v": 1, "type": "Constant", "subtype": "ConstantInt"}
        },
        "step": null
    }
}
list(range(2000))[0:1000:10]
{
    "type": "Subscript",
    "value": {
        "type": "Call",
        "func": {"id": "list", "type": "Name"},
        "args": [
            {
                "type": "Call",
                "func": {"id": "range", "type": "Name"},
                "args": [{"v": 2000, "type": "Constant", "subtype": "ConstantInt"}],
                "keywords": []
            }
        ],
        "keywords": []
    },
    "slice": {
        "type": "Slice",
        "lower": {"v": 0, "type": "Constant", "subtype": "ConstantInt"},
        "upper": {"v": 1000, "type": "Constant", "subtype": "ConstantInt"},
        "step": {"v": 10, "type": "Constant", "subtype": "ConstantInt"}
    }
}

PythonAST
x = 123
{
    "type": "Assign",
    "targets": [{"id": "x", "type": "Name"}],
    "value": {"v": 123, "type": "Constant", "subtype": "ConstantInt"}
}
x = y = f()
{
    "type": "Assign",
    "targets": [
        {"id": "x", "type": "Name"},
        {"id": "y", "type": "Name"}
    ],
    "value": {
        "type": "Call",
        "func": {"id": "f", "type": "Name"},
        "args": [],
        "keywords": []
    }
}
row["foo"] = 123
{
    "type": "Assign",
    "targets": [
        {
            "type": "Subscript",
            "value": {"id": "row", "type": "Name"},
            "slice": {"v": "foo", "type": "Constant", "subtype": "ConstantStr"}
        }
    ],
    "value": {"v": 123, "type": "Constant", "subtype": "ConstantInt"}
}
x, y = arr
{
    "type": "Assign",
    "targets": [
        {
            "type": "Tuple",
            "elts": [
                {"id": "x", "type": "Name"},
                {"id": "y", "type": "Name"}
            ]
        }
    ],
    "value": {"id": "arr", "type": "Name"}
}

PythonAST
x += 2
{
    "type": "AugAssign",
    "target": {"id": "x", "type": "Name"},
    "op": {"type": "Add"},
    "value": {"v": 2, "type": "Constant", "subtype": "ConstantInt"}
}
x /= 2
{
    "type": "AugAssign",
    "target": {"id": "x", "type": "Name"},
    "op": {"type": "Div"},
    "value": {"v": 2, "type": "Constant", "subtype": "ConstantInt"}
}
foo.something -= 2
{
    "type": "AugAssign",
    "target": {
        "type": "Attribute",
        "attr": "something",
        "value": {"id": "foo", "type": "Name"}
    },
    "op": {"type": "Sub"},
    "value": {"v": 2, "type": "Constant", "subtype": "ConstantInt"}
}
row["foo"] -= 2
{
    "type": "AugAssign",
    "target": {
        "type": "Subscript",
        "value": {"id": "row", "type": "Name"},
        "slice": {"v": "foo", "type": "Constant", "subtype": "ConstantStr"}
    },
    "op": {"type": "Sub"},
    "value": {"v": 2, "type": "Constant", "subtype": "ConstantInt"}
}

See BinOp for other supported operators.

PythonAST
not x
{
    "type": "UnaryOp",
    "op": {"type": "Not"},
    "operand": {"id": "x", "type": "Name"}
}

PythonAST
~x
{
    "type": "UnaryOp",
    "op": {"type": "Invert"},
    "operand": {"id": "x", "type": "Name"}
}

PythonAST
+x
{
    "type": "UnaryOp",
    "op": {"type": "UAdd"},
    "operand": {"id": "x", "type": "Name"}
}

PythonAST
-x
{
    "type": "UnaryOp",
    "op": {"type": "USub"},
    "operand": {"id": "x", "type": "Name"}
}

PythonAST
x and y
{
    "type": "BoolOp",
    "op": {"type": "And"},
    "values": [
        {"id": "x", "type": "Name"},
        {"id": "y", "type": "Name"}
    ]
}
x and y and z
{
    "type": "BoolOp",
    "op": {"type": "And"},
    "values": [
        {"id": "x", "type": "Name"},
        {"id": "y", "type": "Name"},
        {"id": "z", "type": "Name"}
    ]
}

PythonAST
x or y
{
    "type": "BoolOp",
    "op": {"type": "Or"},
    "values": [
        {"id": "x", "type": "Name"},
        {"id": "y", "type": "Name"}
    ]
}
x or y or z
{
    "type": "BoolOp",
    "op": {"type": "Or"},
    "values": [
        {"id": "x", "type": "Name"},
        {"id": "y", "type": "Name"},
        {"id": "z", "type": "Name"}
    ]
}

PythonAST
x * y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "Mult"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
x / y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "Div"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
x + y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "Add"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
x - y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "Sub"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
x % y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "Mod"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
x**y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "Pow"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
x @ y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "MatMult"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
x // y
{
    "type": "BinOp",
    "left": {"id": "x", "type": "Name"},
    "op": {"type": "FloorDiv"},
    "right": {"id": "y", "type": "Name"}
}

PythonAST
0b0110 & 0b0011
{
    "type": "BinOp",
    "left": {"v": "0b 0110", "type": "Constant", "subtype": "ConstantIntBinaryDigits"},
    "op": {"type": "BitAnd"},
    "right": {"v": "0b 0011", "type": "Constant", "subtype": "ConstantIntBinaryDigits"}
}

PythonAST
0b0110 | 0b0011
{
    "type": "BinOp",
    "left": {"v": "0b 0110", "type": "Constant", "subtype": "ConstantIntBinaryDigits"},
    "op": {"type": "BitOr"},
    "right": {"v": "0b 0011", "type": "Constant", "subtype": "ConstantIntBinaryDigits"}
}

PythonAST
0b0110 ^ 0b0011
{
    "type": "BinOp",
    "left": {"v": "0b 0110", "type": "Constant", "subtype": "ConstantIntBinaryDigits"},
    "op": {"type": "BitXor"},
    "right": {"v": "0b 0011", "type": "Constant", "subtype": "ConstantIntBinaryDigits"}
}

PythonAST
0b0110 << 1
{
    "type": "BinOp",
    "left": {"v": "0b 0110", "type": "Constant", "subtype": "ConstantIntBinaryDigits"},
    "op": {"type": "LShift"},
    "right": {"v": 1, "type": "Constant", "subtype": "ConstantInt"}
}

PythonAST
0b0110 >> 1
{
    "type": "BinOp",
    "left": {"v": "0b 0110", "type": "Constant", "subtype": "ConstantIntBinaryDigits"},
    "op": {"type": "RShift"},
    "right": {"v": 1, "type": "Constant", "subtype": "ConstantInt"}
}

PythonAST
x == y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "Eq"}],
    "comparators": [{"id": "y", "type": "Name"}]
}

PythonAST
x != y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "NotEq"}],
    "comparators": [{"id": "y", "type": "Name"}]
}

PythonAST
x < y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "Lt"}],
    "comparators": [{"id": "y", "type": "Name"}]
}
x < y <= z
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [
        {"type": "Lt"},
        {"type": "LtE"}
    ],
    "comparators": [
        {"id": "y", "type": "Name"},
        {"id": "z", "type": "Name"}
    ]
}

PythonAST
x <= y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "LtE"}],
    "comparators": [{"id": "y", "type": "Name"}]
}
x < y <= z
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [
        {"type": "Lt"},
        {"type": "LtE"}
    ],
    "comparators": [
        {"id": "y", "type": "Name"},
        {"id": "z", "type": "Name"}
    ]
}

PythonAST
x > y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "Gt"}],
    "comparators": [{"id": "y", "type": "Name"}]
}

PythonAST
x >= y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "GtE"}],
    "comparators": [{"id": "y", "type": "Name"}]
}

PythonAST
x is True
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "Is"}],
    "comparators": [{"type": "Constant", "subtype": "ConstantTrue"}]
}

PythonAST
x is not None
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "IsNot"}],
    "comparators": [{"type": "Constant", "subtype": "ConstantNone"}]
}

PythonAST
x in y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "In"}],
    "comparators": [{"id": "y", "type": "Name"}]
}

PythonAST
x not in y
{
    "type": "Compare",
    "left": {"id": "x", "type": "Name"},
    "ops": [{"type": "NotIn"}],
    "comparators": [{"id": "y", "type": "Name"}]
}

PythonAST
return
{
    "type": "Return",
    "value": null
}
return x
{
    "type": "Return",
    "value": {"id": "x", "type": "Name"}
}
return x, y
{
    "type": "Return",
    "value": {
        "type": "Tuple",
        "elts": [
            {"id": "x", "type": "Name"},
            {"id": "y", "type": "Name"}
        ]
    }
}

PythonAST
break
{"type": "Break"}

PythonAST
continue
{"type": "Continue"}

PythonAST
pass
{"type": "Pass"}

PythonAST
assert x
{
    "type": "Assert",
    "test": {"id": "x", "type": "Name"},
    "msg": null
}
assert x, msg
{
    "type": "Assert",
    "test": {"id": "x", "type": "Name"},
    "msg": {"id": "msg", "type": "Name"}
}

PythonAST
raise NotImplementedError
{
    "type": "Raise",
    "exc": {"id": "NotImplementedError", "type": "Name"},
    "cause": null
}
raise Exception("Foo")
{
    "type": "Raise",
    "exc": {
        "type": "Call",
        "func": {"id": "Exception", "type": "Name"},
        "args": [{"v": "Foo", "type": "Constant", "subtype": "ConstantStr"}],
        "keywords": []
    },
    "cause": null
}
raise FooError(x, y) from upstream_err
{
    "type": "Raise",
    "exc": {
        "type": "Call",
        "func": {"id": "FooError", "type": "Name"},
        "args": [
            {"id": "x", "type": "Name"},
            {"id": "y", "type": "Name"}
        ],
        "keywords": []
    },
    "cause": {"id": "upstream_err", "type": "Name"}
}

PythonAST
x if y else z
{
    "type": "IfExp",
    "body": {"id": "x", "type": "Name"},
    "test": {"id": "y", "type": "Name"},
    "orelse": {"id": "z", "type": "Name"}
}

PythonAST
if x:
    pass
{
    "type": "If",
    "test": {"id": "x", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": []
}
if x:
    pass
else:
    pass
{
    "type": "If",
    "test": {"id": "x", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": [{"type": "Pass"}]
}
if x:
    pass
elif y:
    pass
{
    "type": "If",
    "test": {"id": "x", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": [
        {
            "type": "If",
            "test": {"id": "y", "type": "Name"},
            "body": [{"type": "Pass"}],
            "orelse": []
        }
    ]
}
if x:
    pass
elif y:
    pass
else:
    pass
{
    "type": "If",
    "test": {"id": "x", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": [
        {
            "type": "If",
            "test": {"id": "y", "type": "Name"},
            "body": [{"type": "Pass"}],
            "orelse": [{"type": "Pass"}]
        }
    ]
}
if x:
    pass
elif y:
    pass
elif z:
    pass
else:
    pass
{
    "type": "If",
    "test": {"id": "x", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": [
        {
            "type": "If",
            "test": {"id": "y", "type": "Name"},
            "body": [{"type": "Pass"}],
            "orelse": [
                {
                    "type": "If",
                    "test": {"id": "z", "type": "Name"},
                    "body": [{"type": "Pass"}],
                    "orelse": [{"type": "Pass"}]
                }
            ]
        }
    ]
}

PythonAST
for x in arr:
    pass
{
    "type": "For",
    "target": {"id": "x", "type": "Name"},
    "iter": {"id": "arr", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": []
}
for i, x in enumerate(arr):
    pass
{
    "type": "For",
    "target": {
        "type": "Tuple",
        "elts": [
            {"id": "i", "type": "Name"},
            {"id": "x", "type": "Name"}
        ]
    },
    "iter": {
        "type": "Call",
        "func": {"id": "enumerate", "type": "Name"},
        "args": [{"id": "arr", "type": "Name"}],
        "keywords": []
    },
    "body": [{"type": "Pass"}],
    "orelse": []
}
for i in range(len(arr)):
    pass
{
    "type": "For",
    "target": {"id": "i", "type": "Name"},
    "iter": {
        "type": "Call",
        "func": {"id": "range", "type": "Name"},
        "args": [
            {
                "type": "Call",
                "func": {"id": "len", "type": "Name"},
                "args": [{"id": "arr", "type": "Name"}],
                "keywords": []
            }
        ],
        "keywords": []
    },
    "body": [{"type": "Pass"}],
    "orelse": []
}
for x in arr:
    pass
else:
    pass
{
    "type": "For",
    "target": {"id": "x", "type": "Name"},
    "iter": {"id": "arr", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": [{"type": "Pass"}]
}

The else block executes after the loop is complete, unless the loop exited due to a break or an exception.

PythonAST
while foo:
    pass
{
    "type": "While",
    "test": {"id": "foo", "type": "Name"},
    "body": [{"type": "Pass"}],
    "orelse": []
}
while i < 10:
    i += 1
else:
    print("Hello from the else block")
{
    "type": "While",
    "test": {
        "type": "Compare",
        "left": {"id": "i", "type": "Name"},
        "ops": [{"type": "Lt"}],
        "comparators": [{"v": 10, "type": "Constant", "subtype": "ConstantInt"}]
    },
    "body": [
        {
            "type": "AugAssign",
            "target": {"id": "i", "type": "Name"},
            "op": {"type": "Add"},
            "value": {"v": 1, "type": "Constant", "subtype": "ConstantInt"}
        }
    ],
    "orelse": [
        {
            "type": "Expr",
            "value": {
                "type": "Call",
                "func": {"id": "print", "type": "Name"},
                "args": [{"v": "Hello from the else block", "type": "Constant", "subtype": "ConstantStr"}],
                "keywords": []
            }
        }
    ]
}

The else block executes after the test has evaluated to false. If that never happens (e.g. due to a break, a return, or an exception), then the else block will never get run.

See FunctionDef or Lambda.

See FunctionDef or Lambda.

PythonAST
def f():
    return 4
{
    "type": "FunctionDef",
    "decorator_list": [],
    "name": "f",
    "args": {
        "type": "arguments",
        "args": [],
        "defaults": [],
        "vararg": null,
        "kwarg": null
    },
    "body": [
        {
            "type": "Return",
            "value": {"v": 4, "type": "Constant", "subtype": "ConstantInt"}
        }
    ]
}
# If you call `f` 100 times, then:
# - `len(arr) == 100`
# - `g` has only neen invoked once
def f(x, y, foo=None, bar=g(), arr=[]):
    arr.append(x)
{
    "type": "FunctionDef",
    "decorator_list": [],
    "name": "f",
    "args": {
        "type": "arguments",
        "args": [
            {
                "type": "arg",
                "arg": "x"
            },
            {
                "type": "arg",
                "arg": "y"
            },
            {
                "type": "arg",
                "arg": "foo"
            },
            {
                "type": "arg",
                "arg": "bar"
            },
            {
                "type": "arg",
                "arg": "arr"
            }
        ],
        "defaults": [
            {"type": "Constant", "subtype": "ConstantNone"},
            {
                "type": "Call",
                "func": {"id": "g", "type": "Name"},
                "args": [],
                "keywords": []
            },
            {
                "type": "List",
                "elts": []
            }
        ],
        "vararg": null,
        "kwarg": null
    },
    "body": [
        {
            "type": "Expr",
            "value": {
                "type": "Call",
                "func": {
                    "type": "Attribute",
                    "attr": "append",
                    "value": {"id": "arr", "type": "Name"}
                },
                "args": [{"id": "x", "type": "Name"}],
                "keywords": []
            }
        }
    ]
}
def f(*foo, **bar):
    pass
{
    "type": "FunctionDef",
    "decorator_list": [],
    "name": "f",
    "args": {
        "type": "arguments",
        "args": [],
        "defaults": [],
        "vararg": {
            "type": "arg",
            "arg": "foo"
        },
        "kwarg": {
            "type": "arg",
            "arg": "bar"
        }
    },
    "body": [{"type": "Pass"}]
}

PythonAST
lambda: 123
{
    "type": "Lambda",
    "args": {
        "type": "arguments",
        "args": [],
        "defaults": [],
        "vararg": null,
        "kwarg": null
    },
    "body": {"v": 123, "type": "Constant", "subtype": "ConstantInt"}
}
lambda x, y=None: x + y
{
    "type": "Lambda",
    "args": {
        "type": "arguments",
        "args": [
            {
                "type": "arg",
                "arg": "x"
            },
            {
                "type": "arg",
                "arg": "y"
            }
        ],
        "defaults": [{"type": "Constant", "subtype": "ConstantNone"}],
        "vararg": null,
        "kwarg": null
    },
    "body": {
        "type": "BinOp",
        "left": {"id": "x", "type": "Name"},
        "op": {"type": "Add"},
        "right": {"id": "y", "type": "Name"}
    }
}

PythonAST
class Foo:
    pass
{
    "type": "ClassDef",
    "decorator_list": [],
    "name": "Foo",
    "bases": [],
    "body": [{"type": "Pass"}]
}
class Foo(Bar, Bar2):
    SOMETHING = 123

    def __init__(self, x):
        self.x = x
{
    "type": "ClassDef",
    "decorator_list": [],
    "name": "Foo",
    "bases": [
        {"id": "Bar", "type": "Name"},
        {"id": "Bar2", "type": "Name"}
    ],
    "body": [
        {
            "type": "Assign",
            "targets": [{"id": "SOMETHING", "type": "Name"}],
            "value": {"v": 123, "type": "Constant", "subtype": "ConstantInt"}
        },
        {
            "type": "FunctionDef",
            "decorator_list": [],
            "name": "__init__",
            "args": {
                "type": "arguments",
                "args": [
                    {
                        "type": "arg",
                        "arg": "self"
                    },
                    {
                        "type": "arg",
                        "arg": "x"
                    }
                ],
                "defaults": [],
                "vararg": null,
                "kwarg": null
            },
            "body": [
                {
                    "type": "Assign",
                    "targets": [
                        {
                            "type": "Attribute",
                            "attr": "x",
                            "value": {"id": "self", "type": "Name"}
                        }
                    ],
                    "value": {"id": "x", "type": "Name"}
                }
            ]
        }
    ]
}

See Call

PythonAST
f(123)
{
    "type": "Call",
    "func": {"id": "f", "type": "Name"},
    "args": [{"v": 123, "type": "Constant", "subtype": "ConstantInt"}],
    "keywords": []
}
f(123, y=456, *a, **b)
{
    "type": "Call",
    "func": {"id": "f", "type": "Name"},
    "args": [
        {"v": 123, "type": "Constant", "subtype": "ConstantInt"},
        {
            "type": "Starred",
            "value": {"id": "a", "type": "Name"}
        }
    ],
    "keywords": [
        {
            "type": "keyword",
            "arg": "y",
            "value": {"v": 456, "type": "Constant", "subtype": "ConstantInt"}
        },
        {
            "type": "keyword",
            "arg": null,
            "value": {"id": "b", "type": "Name"}
        }
    ]
}

See Import or ImportFrom

PythonAST
import foo, numpy as np
{
    "type": "Import",
    "names": [
        {
            "type": "alias",
            "asname": null,
            "name": "foo"
        },
        {
            "type": "alias",
            "asname": "np",
            "name": "numpy"
        }
    ]
}

PythonAST
from foo import *
{
    "type": "ImportFrom",
    "module": "foo",
    "names": [
        {
            "type": "alias",
            "asname": null,
            "name": "*"
        }
    ]
}
from foo import bar, bar2 as b
{
    "type": "ImportFrom",
    "module": "foo",
    "names": [
        {
            "type": "alias",
            "asname": null,
            "name": "bar"
        },
        {
            "type": "alias",
            "asname": "b",
            "name": "bar2"
        }
    ]
}

PythonAST
x
foo.bar
{
    "type": "Module",
    "body": [
        {
            "type": "Expr",
            "value": {"id": "x", "type": "Name"}
        },
        {
            "type": "Expr",
            "value": {"id": "foo.bar", "type": "Name"}
        }
    ]
}

PythonAST
x
foo.bar
{
    "type": "Module",
    "body": [
        {
            "type": "Expr",
            "value": {"id": "x", "type": "Name"}
        },
        {
            "type": "Expr",
            "value": {"id": "foo.bar", "type": "Name"}
        }
    ]
}

This is not an official node type — i.e. CPython's ast.parse() does not create any nodes for comments.