b = a*+2 是有效语法。为什么?

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

为什么 python (3.7.9) 允许这种语法?

a = 3
b = a*+2

它觉得这很烦人,因为如果你想打字 b = a**2 在您改为 b = a*+2 的德语键盘布局上,它可能会很快发生。在没有语法错误的情况下,找到这样的错误可能非常耗时。此外,它违反了通常的数学规则,即相邻的运算符应该用括号分隔。

这是因为 python supports unary arithmetic operations. You can also inspect how python compiles down the source expression to abstract syntax tree 使用了 ast 模块。

>>> 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=[])

另见