[Python-Dev] assignment expressions: an alternative proposal

Chris Angelico rosuav at gmail.com
Tue Apr 24 10:56:31 EDT 2018


On Wed, Apr 25, 2018 at 12:23 AM, Yury Selivanov
<yselivanov.ml at gmail.com> wrote:
> On Tue, Apr 24, 2018 at 10:07 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>
>>> "=" is always an assignment.
>>> "==" is always an equality check.
>>
>> That's not the distinction I meant, I meant the difficulty of
>> explaining the discrepancies in this list:
>>
>> a = 1 # Assignment
>> (a = 1) # Also assignment
>>
>> a, b = 1, 2 # Tuple assignment
>> (a, b = 1, 2) # SyntaxError. Why?
>>
>> ...
>> Whereas if binding expressions use a different symbol, the question is
>> far less likely to arise, and if it does come up, then the answer is
>> the same as the one for def statements vs lambda expressions: because
>> one is a statement, and the other is an expression.
>
> A lot of other questions arise though.  PEP 572 proposes:
>
> a = 1  # assignment
> a := 1  # also assignment
> (a := 1)  # also assignment
> (a = 1)  # error, why?

Your third example is just the same as the second, with parentheses
around it. In most of Python, parentheses (if legal) have no effect
other than grouping; "a + b * c" is the same thing as "(a + b) * c",
just done in the other order. The last one is a clear demonstration
that "=" is a statement, not an expression. Are people confused by
this sort of thing:

if x > 1:
    print("x is more than 1")
(if x > 1:)
    print("SyntaxError")

? Yes, the word 'if' does have meaning in an expression context, and
yes, it has a similar meaning to the 'if' statement, but people don't
parenthesize entire statements. You try that with assignment, you get
an error, and bam, it's obvious that you ran into this particular
case.

ChrisA


More information about the Python-Dev mailing list