From c3d158f21f6cbf112bcc72e4721b8613b0c38aa0 Mon Sep 17 00:00:00 2001 From: Craig Barratt <19445341+craigbarratt@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:21:43 -0800 Subject: [PATCH] Update augmented assignment targets in place, as Python does (#944) ast_augassign() ran x += y as x = x + y, so in-place methods (__iadd__, __ior__ and so on) were never called: y = x; x += [3] left y unchanged, list += tuple raised TypeError, and the target's object and index were evaluated twice (counts[key()] += 1 called key() twice). It also toggled the shared AST node's ctx across an await. Evaluate the target's object and index once, apply the matching operator.iadd()/ior()/... function, which calls the in-place method or falls back to the binary one as Python does, and store the result back. State variables and their attributes, properties and pyscript classes' own in-place methods keep working. Fixes #944 Co-Authored-By: Claude Opus 5.5 --- custom_components/pyscript/eval.py | 46 +++++++++++-- tests/test_unit_eval.py | 102 +++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 5 deletions(-) diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index 281de59..1f87fc4 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -3,11 +3,13 @@ import ast import asyncio import builtins +import copy import functools import importlib import inspect import keyword import logging +import operator import sys import time import traceback @@ -427,6 +429,24 @@ def unwrap_stop_iteration(exc): return exc +# the in-place operator function for each augmented assignment operator +AUGASSIGN_OPS = { + ast.Add: operator.iadd, + ast.Sub: operator.isub, + ast.Mult: operator.imul, + ast.MatMult: operator.imatmul, + ast.Div: operator.itruediv, + ast.FloorDiv: operator.ifloordiv, + ast.Mod: operator.imod, + ast.Pow: operator.ipow, + ast.LShift: operator.ilshift, + ast.RShift: operator.irshift, + ast.BitOr: operator.ior, + ast.BitXor: operator.ixor, + ast.BitAnd: operator.iand, +} + + # special methods that pyscript leaves as they are: it calls __init__ and __new__ itself, __del__ # runs whenever the object is freed, Python calls __getattribute__, __setattr__ and __delattr__ for # every attribute access, which pyscript handles itself (eg, for @property), and the async ones @@ -1662,11 +1682,27 @@ async def ast_assign(self, arg): await self.recurse_assign(target, rhs) async def ast_augassign(self, arg): - """Execute augmented assignment statement (lhs = value).""" - arg.target.ctx = ast.Load() - new_val = await self.aeval(ast.BinOp(left=arg.target, op=arg.op, right=arg.value)) - arg.target.ctx = ast.Store() - await self.recurse_assign(arg.target, new_val) + """Execute augmented assignment statement (lhs = value).""" + # + # as in Python, evaluate the target's object and index once, update the value in place + # if it supports that (eg, list +=), and store the result back + # + target = arg.target + if isinstance(target, ast.Subscript): + obj, index = await self.aeval(target.value), await self.aeval(target.slice) + target = ast.copy_location( + ast.Subscript(value=ast.Constant(obj), slice=ast.Constant(index)), target + ) + elif isinstance(target, ast.Attribute) and await self.ast_attribute_collapse(target) is None: + obj = await self.aeval(target.value) + target = ast.copy_location(ast.Attribute(value=ast.Constant(obj), attr=target.attr), target) + else: + # a name, or a state variable or its attribute + target = copy.copy(target) + target.ctx = ast.Load() + new_val = AUGASSIGN_OPS[type(arg.op)](await self.aeval(target), await self.aeval(arg.value)) + target.ctx = ast.Store() + await self.recurse_assign(target, new_val) async def ast_annassign(self, arg): """Execute type hint assignment statement and track __annotations__.""" diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index c610c8a..77c65d6 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -167,6 +167,108 @@ ["x: int = [10, 20]; x", [10, 20]], ["Foo = type('Foo', (), {'x': 100}); Foo.x = 10; Foo.x", 10], ["Foo = type('Foo', (), {'x': 100}); Foo.x += 10; Foo.x", 110], + # augmented assignment updates in place, evaluates the target once, and calls __iadd__ etc + ["x = [1, 2]; y = x; x += [3]; [x, y, x is y]", [[1, 2, 3], [1, 2, 3], True]], + ["x = [1]; x += (2, 3); x", [1, 2, 3]], + ["d = {'a': 1}; e = d; d |= {'b': 2}; [e, d is e]", [{"a": 1, "b": 2}, True]], + [ + "s = {1, 2, 3}; t = s; s -= {1}; s |= {9}; s &= {2, 9}; s ^= {5}; [sorted(t), s is t]", + [[2, 5, 9], True], + ], + ["a = 7; a -= 2; a *= 3; a //= 4; a %= 3; a **= 3; b = 7.0; b /= 2; [a, b]", [0, 3.5]], + ["a = 8; a <<= 2; a >>= 1; a |= 1; a ^= 3; a &= 6; a", 2], + ["s = 'a'; t = s; s += 'b'; t = (1,); u = t; t += (2,); [s, t, u]", ["ab", (1, 2), (1,)]], + ["import collections; q = collections.deque([1]); q += [2, 3]; list(q)", [1, 2, 3]], + ["x = [1, 2, 3, 4]; x[1:3] += [9]; x", [1, 2, 3, 9, 4]], + ["d = {'a': [1]}; inner = d['a']; d['a'] += [2]; [inner, d['a'] is inner]", [[1, 2], True]], + [ + """ +calls = [] +def key(): + calls.append('key') + return 'k' +class Obj: + pass +obj = Obj() +obj.items = [1] +def get_obj(): + calls.append('obj') + return obj +counts = {'k': 0} +counts[key()] += 1 +get_obj().items += [2] +[counts, obj.items, calls] +""", + [{"k": 1}, [1, 2], ["key", "obj"]], + ], + [ + """ +class Obj: + pass +obj = Obj() +obj.items = [1] +alias = obj.items +obj.items += [2] +obj.sub = Obj() +obj.sub.n = 1 +obj.sub.n += 5 +[alias, obj.items is alias, obj.sub.n] +""", + [[1, 2], True, 6], + ], + [ + """ +calls = [] +class Prop: + def __init__(self): + self._items = [1] + @property + def items(self): + calls.append('get') + return self._items + @items.setter + def items(self, value): + calls.append('set') + self._items = value +p = Prop() +p.items += [2] +[p._items, calls] +""", + [[1, 2], ["get", "set"]], + ], + [ + """ +class InPlace: + def __init__(self): + self.n = 0 + def __iadd__(self, other): + self.n += other + return self +class Plain: + def __init__(self, n): + self.n = n + def __add__(self, other): + return Plain(self.n + other) +a = InPlace() +a_alias = a +a += 5 +b = Plain(1) +b_alias = b +b += 5 +[a_alias.n, a is a_alias, b.n, b_alias.n] +""", + [5, True, 6, 1], + ], + [ + """ +def add_tag(tags): + tags += ['new'] + return tags +tags = ['a'] +[add_tag(tags) is tags, tags] +""", + [True, ["a", "new"]], + ], [ """ from enum import IntEnum