all Python 3astterm
ast.unaryop
operators
The abstract base class of unary operators: Not (not), USub (-x), UAdd (+x) and Invert (~x). An instance is the op field of a UnaryOp node.
Syntax
isinstance(node.op, ast.unaryop)
A negative number in code is not a constant: -5 parses as UnaryOp(USub, Constant(5)), so searching for a Constant with value < 0 finds nothing. ast.literal_eval understands this and returns -5. The logical not is also a unaryop, not a boolop.
Examples
import ast
e = ast.parse('-5', mode='eval').body
print(type(e).__name__, type(e.op).__name__, e.operand.value) # → UnaryOp USub 5
print(ast.literal_eval('-5')) # → -5
print(type(ast.parse('not x', mode='eval').body.op).__name__) # → Not
See also
Open in the full glossarydocs.python.orgReport an inaccuracy