Files
micropython/tests/ports/webassembly/py_proxy_identity.mjs
Damien George ffa98cb014 webassembly/proxy_js: Reuse JsProxy ref if object matches.
This reduces memory use by reusing objects, and improves identity/equality
relationships of JavaScript objects on the Python side.

In 77bd8fe5b8 PyProxy's were reused when the
same Python object was proxied across to JavaScript.  This commit does the
same thing but for JsProxy's going from JS to Python.  If an existing
JsProxy reference exists for the JS object about to be proxied across, then
it's reused.

This helps reduce the number of alive objects (memory use), and, more
importantly, improves equality relationships of JavaScript objects on the
Python side.  Eg we now get, on the Python side:

    import js

    print(js.Object == js.Object)

that prints True.  Previously it was False.

Note that this change does not make identity work with `is`, for example
`js.Object is js.Object` is actually False.  With more work that could be
made True but for now we leave that as-is.

The behaviour with this commit matches Pyodide semantics.

Signed-off-by: Damien George <damien@micropython.org>
2025-07-31 11:40:50 +10:00

36 lines
873 B
JavaScript

// Test identity of PyProxy when they are the same Python object.
const mp = await (await import(process.argv[2])).loadMicroPython();
mp.runPython(`
l = []
`);
const l1 = mp.globals.get("l");
const l2 = mp.globals.get("l");
console.log(l1, l2);
console.log(l1 === l2);
globalThis.eventTarget = new EventTarget();
globalThis.event = new Event("event");
mp.runPython(`
import js
def callback(ev):
print("callback", ev)
js.eventTarget.addEventListener("event", callback)
js.eventTarget.dispatchEvent(js.event)
js.eventTarget.removeEventListener("event", callback)
js.eventTarget.dispatchEvent(js.event)
print("Object equality")
print(js.Object == js.Object)
print(js.Object.assign == js.Object.assign)
print("Array equality")
print(js.Array == js.Array)
print(js.Array.prototype == js.Array.prototype)
print(js.Array.prototype.push == js.Array.prototype.push)
`);