2 ms·
RHS seems right to me because it means the actions on the LHS happen consecutively. To expand your example a bit: class ShoutyContainer: def __setitem
by duckerude 8y ago
RHS seems right to me because it means the actions on the LHS happen consecutively.
To expand your example a bit:
class ShoutyContainer:
def __setitem__(self, index, value):
print("Assignment")
def lhs(): print("LHS")
def rhs(): print("RHS")
a = ShoutyContainer()
a[lhs()] = rhs()
Yields:
RHS
LHS
Assignment
If LHS were evaluated first, then it would be separated from the final assignment step by the RHS evaluation. That would be odd.
- alangpierce 8y agoI 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.