Python Glossary Русский

all Python 3astterm

ast.USub

operators

The unary minus operator -x in the op field of a UnaryOp.

Syntax

ast.USub()

USub is why the tree has no negative literals: -1 is UnaryOp(USub, Constant(1)), so isinstance(node, ast.Constant) is false for -1. Unary minus binds looser than **, so -2 ** 2 equals -4. ast.unparse keeps the sign, but anything hunting for negative numbers must match the UnaryOp, USub and Constant triple.

Examples

import ast
n = ast.parse('-1', mode='eval').body
print(type(n).__name__, type(n.op).__name__, isinstance(n, ast.Constant))  # → UnaryOp USub False
print(ast.unparse(n))  # → -1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy