What is the reason the Python Walrus Operator only works with variable names?

79 views Asked by At

Valid code:

x, y, z = 1, 2, 3
print(x := x + y)
print(x, y, z)

Invalid code:

arr = [1, 2, 3]
print(arr[0] := arr[0] + arr[1])
print(arr)

Error:

SyntaxError: cannot use assignment expressions with subscript

Another example in which it would be useful:

bool_index = # Problem cells in the array
assert not any(bool_index), "Problems here: \n{}".format(np.full(arr.shape, ".")[bool_index] := "X")

The above snippet would ideally look something like this:

Problems here:
array([['.', '.', '.', '.', '.', '.', '.', '.', '.'],
       ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
       ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
       ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
       ['.', '.', '.', 'X', '.', '.', '.', '.', '.'],
       ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
       ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
       ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
       ['.', '.', '.', '.', '.', '.', '.', '.', '.']], dtype='<U1')

However, we would have to generate that array in a variable ahead of time to mark the "X" (even if we would never show it) or we would have to dedicate additional lines to adding a function which only runs if called by the assert (the function being at least three lines due to still requiring a variable).

I understand the most recent example I gave may be bad style, but small little would-be one-liners of this sort are fairly common in research code and things that would normally fit nicely into a list-comprehension must be instead written in a for-loop due to being unable to write these sorts of expressions.

Does this limitation of the Walrus Operator exist due to any limitation in parsing the language? Was the implementation decided against? Or is this functionality coming in some future version of python? What is the reason for this limitation?

0

There are 0 answers