Files
micropython/tests/basics/weakref_multiple_refs.py
T
Damien George 6f96d260e6 webassembly/variants/pyscript: Enable weakref module and add tests.
The webassembly port needs some additional weakref tests due to the fact
that garbage collection only happens when Python execution finishes and
JavaScript resumes.

The `tests/ports/webassembly/heap_expand.py` expected output also needs to
be updated because the amount of GC heap got smaller (weakref WTB takes
some of the available RAM).

Signed-off-by: Damien George <damien@micropython.org>
2026-03-22 23:13:26 +11:00

37 lines
905 B
Python

# Test weakref when multiple weak references are active.
#
# This test has different output to CPython due to the order that MicroPython
# executes weak reference callbacks.
try:
import weakref
except ImportError:
print("SKIP")
raise SystemExit
# gc module must be available if weakref is.
import gc
class A:
def __str__(self):
return "<A object>"
def test():
global r1, r2 # needed for webassembly port to retain references to them
print("test having multiple ref and finalize objects referencing the same thing")
a = A()
r1 = weakref.ref(a, lambda r: print("ref1", r()))
f1 = weakref.finalize(a, lambda: print("finalize1"))
r2 = weakref.ref(a, lambda r: print("ref2", r()))
f2 = weakref.finalize(a, lambda: print("finalize2"))
print(r1(), f1.alive, r2(), f2.alive)
a = None
clean_the_stack = [0, 0, 0, 0]
gc.collect()
test()