Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is b=(a+=1) an invalid syntax in python?

If I write the following in python, I get a syntax error, why so?

a = 1
b = (a+=1)

I am using python version 2.7

what I get when I run it, the following:

>>> a = 1
>>> b = (a +=1)
  File "<stdin>", line 1
    b = (a +=1)
        ^
SyntaxError: invalid syntax
>>>
like image 977
Har Avatar asked Dec 09 '22 10:12

Har


1 Answers

Unlike in some other languages, assignment (including augmented assignment, like +=) in Python is not an expression. This also affects things like this:

(a=1) > 2

which is legal in C, and several other languages.

The reason generally given for this is because it helps to prevent a class of bugs like this:

if a = 1: # instead of ==
    pass
else:
    pass

since assignment isn't an expression, this is a SyntaxError in Python. In the equivalent C code, it is a subtle bug where the variable will be modified rather than checked, the check will always be true (in C, like in Python, a non-zero integer is always truthy), and the else block can never fire.

You can still do chained assignment in Python, so this works:

>>> a = 1 
>>> a = b = a+1
>>> a
2
>>> b
2
like image 96
lvc Avatar answered Dec 11 '22 08:12

lvc