skulpt / skulpt

Skulpt is a Javascript implementation of the Python programming language
Other
3.34k stars 894 forks source link

ffi: preserve identity of methods into javascript #1531

Closed s-cork closed 1 year ago

s-cork commented 1 year ago

Use case

import document
from time import sleep

class Foo:
    def on_mount(self):
        document.addEventListener("click", self.on_click)

    def on_cleanup(self):
        document.removeEventListener("click", self.on_click)

    def on_click(self, event):
        print("document was clicked")

foo = Foo()
foo.on_mount()
sleep(3)
foo.on_cleanup()

We would expect that the above code to successfully clean up the click event handler But currently this doesn't work

the equivalent code would work in javascript because bound methods are identical whereas in python two methods are not identical

>>> foo.on_click is foo.on_click
False
>>> foo.on_click == foo.on_click
True
>>> class Foo { bar() {}}
>>> var foo = new Foo()
>>> foo.bar === foo.bar
true

This is a big gotcha for event handlers in the interop between python and javascript This PR uses a weak cache to always send the same method into javascript