Python Glossary Русский

all Python 3astterm

ast.Invert

operators

The marker for the unary operator ~ in an ast tree: it sits in UnaryOp.op and has no fields.

Syntax

ast.Invert()

Do not confuse it with Not: '~x' is bitwise NOT (Invert), 'not x' is logical (Not), both stored in UnaryOp.op. '-5' is a UnaryOp too (USub over Constant 5), not a negative constant, although ast.literal_eval accepts such numbers. ~True equals -2, and since 3.12 that expression emits a DeprecationWarning at run time — the tree is unaffected.

Examples

import ast
u = ast.parse('~x', mode='eval').body
print(type(u).__name__, type(u.op).__name__)  # → UnaryOp Invert
print(type(ast.parse('not x', mode='eval').body.op).__name__)  # → Not

See also

Open in the full glossarydocs.python.orgReport an inaccuracy