Python Glossary Русский

all Python 3astterm

ast.UAdd

operators

The unary plus operator +x in the op field of a UnaryOp.

Syntax

ast.UAdd()

Unary plus is not a no-op: it calls __pos__, and for Decimal, for example, it rounds the value to the context precision. That is why +5 in the tree is UnaryOp(UAdd, Constant(5)) rather than a Constant, and an optimiser may not drop it. The binary + is Add in a BinOp.

Examples

import ast
n = ast.parse('+5', mode='eval').body
print(type(n).__name__, type(n.op).__name__)  # → UnaryOp UAdd
from decimal import Decimal, localcontext
with localcontext() as ctx:
    ctx.prec = 3
    print(+Decimal('1.23456'))  # → 1.23

See also

Open in the full glossarydocs.python.orgReport an inaccuracy