3 ms·
I think it depends on how you think about it. As mentioned elsewhere, "=" is a special statement syntax rather than an operator in Python, but if you were to th
by alangpierce 8y ago
I think it depends on how you think about it. As mentioned elsewhere, "=" is a special statement syntax rather than an operator in Python, but if you were to think of it like an operator, it would be evaluated in three phases: (1) evaluate one side, (2) evaluate the other side, (3) perform operation. The __setitem__ method defines how the left side participates in step 3, but IMO there's a separate LHS evaluation step that's independent of the assignment itself.
You might call this code snippet analogous:
class ShoutyNumber:
def __init__(self, n):
self.n = n
print(f'Created {self.n}')
def __add__(self, other):
print(f'Added with {self.n}')
return self.n + other.n
ShoutyNumber(1) + ShoutyNumber(2)
Yields:
Created 1
Created 2
Added with 1
But I understand that in some mental models and some implementations, it's cleaner to have the entire RHS value ready before starting any evaluation of the LHS. I think that avoids the need to have "assignable reference" as a special type of expression result.