pyscript icon indicating copy to clipboard operation
pyscript copied to clipboard

Closure captures a caller’s argument after #924

Open dmamelin opened this issue 1 week ago • 1 comments

After #924, calling a factory through another function can silently change the value its closure returns. Reproduced by loading this script.

label = "global"

def make():
    def read():
        return label
    return read

def caller(label):
    return make()

read_label = caller("caller")
assert read_label() == "global"

On CPython 3.14 and pyscript 933e177, the assertion passes. On 148e2d3, read_label() returns "caller" and the assertion fails. Calling make()() directly still returns "global" on all three.

read is defined inside make, so its free name label should resolve to the module variable regardless of who calls make.

@HoneyBearTech

dmamelin avatar Nov 24 '26 12:11 dmamelin

Thanks @dmamelin for the clear report and the small script. I can reproduce it: on 148e2d3 read_label() returns "caller", and on 933e177 it returns "global", as CPython does.

The cause. When pyscript creates an inner function, EvalFunc.resolve_nonlocals() in eval.py decides which outside variables the inner function shares. It searches the symbol tables of the functions that are currently running (sym_table_stack), and takes the first one that keeps the name as a shared variable. Python only looks in the functions the inner function is written inside. In your script, read is written inside make, so the search should never reach caller, but it does, because caller is the function that called make.

Why #924 exposed it. Before #924, only a function with an inner function or a lambda kept its variables in the shared form that this search picks up, so most callers were skipped. The bug was already there for those functions. On 933e177, your script also gives "caller" if caller contains a lambda:

label = "global"

def make():
    def read():
        return label
    return read

def caller(label):
    f = lambda: label
    return make()

read_label = caller("caller")
assert read_label() == "global"

#924 made every function keep its variables in the shared form, so now it happens with any caller.

The fix. I'll change the search so an inner function only shares variables from the functions it is written inside, and add both scripts to the tests that compare pyscript with CPython, as written and with an inner function. I'll open a PR for it soon.

HoneyBearTech avatar Nov 24 '26 13:11 HoneyBearTech