Python Glossary Русский

Python 3.6+astterm

ast.Constant

literals

A literal node: a number, string, bytes, True, False, None or the ellipsis. Since Python 3.8 the parser emits it for every constant instead of Num, Str and the others.

Syntax

ast.Constant(value, kind=None)

The value is in the value field, and the kind of literal is told apart with isinstance(node.value, int) and the like — keep in mind that True passes as an int too. A negative number is not a constant: -1 parses into UnaryOp(USub, Constant(1)), so searching Constant nodes misses negative literals. The kind field is 'u' only for a string with the u'...' prefix, otherwise None. The old Num and Str nodes with the n and s fields were removed in 3.14.

Examples

import ast
for src in ['42', "'hi'", 'None', '...']:
    node = ast.parse(src, mode='eval').body
    print(type(node).__name__, repr(node.value))
# → Constant 42 / Constant 'hi' / Constant None / Constant Ellipsis
import ast
node = ast.parse('-1', mode='eval').body
print(type(node).__name__, node.operand.value)  # → UnaryOp 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy