all Python 3astterm
ast.UnaryOp
expressions
Node for a unary operation: op is UAdd, USub, Not or Invert, operand is the expression it applies to.
Syntax
ast.UnaryOp(op, operand)
A negative number in source is not a Constant: -5 parses as UnaryOp(USub, Constant(5)), so analysis that looks for numbers via Constant loses the sign, even though ast.literal_eval accepts -5. Precedence is another trap: -2 ** 2 is a UnaryOp whose operand is the BinOp 2 ** 2, so the result is -4. Logical not is a UnaryOp too, while and/or are BoolOp.
Examples
import ast
n = ast.parse('-5', mode='eval').body
print(type(n).__name__, type(n.op).__name__, n.operand.value) # → UnaryOp USub 5
print(ast.literal_eval('-5')) # → -5
import ast
n = ast.parse('-2 ** 2', mode='eval').body
print(type(n).__name__, type(n.operand).__name__, -2 ** 2) # → UnaryOp BinOp -4
See also
Open in the full glossarydocs.python.orgReport an inaccuracy