cakelover
cakelover

Reputation: 177

b = a*+2 is valid syntax. Why?

Why does python (3.7.9) allow this syntax?

a = 3
b = a*+2

It find this annoying because if you want to type b = a**2 it can happen very quickly on the german keyboard layout that you write instead b = a*+2. With no sytnax error, finding such a bug can be very time consuming. Furthermore, it violates the usual mathematical rule that adjacent operators should be separated with brackets.

Upvotes: 0

Views: 189

Answers (1)

user459872
user459872

Reputation: 24817

This is because python supports unary arithmetic operations. You can also inspect how python compiles down the source expression to abstract syntax tree using ast module.

>>> import ast
>>>
>>> print(ast.dump(ast.parse("b = a*+2"), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='b', ctx=Store())],
            value=BinOp(
                left=Name(id='a', ctx=Load()),
                op=Mult(),
                right=UnaryOp(
                    op=UAdd(),
                    operand=Constant(value=2))))],
    type_ignores=[])

See also:

Upvotes: 6

Related Questions