Unable to update Python dicts from JS

Hi Anvil and friends :slight_smile:

I’m trying to pass a dict from Python to a JS function, having it fill the data, and then using it back in Python. However, the dictionary on the Python end doesn’t reflect changes made by JS.

I created a MRE in the clone link below. The code has a button that when pressed calls a JS script function with a Python dict. The JS function returns a random string and adds a value to the passed dictionary. The Python code then finally throws the result into a textbox.

When running the app you can see that the new key added to the dict by the JS function is absent after its return.

Is this behavior expected or should it be possible to update the dict from Javascript?

Cheers!

I honestly have no idea why the JS is behaving that way, but I don’t see a good reason either way why the function needs to be written in JS.

I had Chat GPT refactor the randomizer function itself and the integrated it into your app:

Thanks Duncan. In my original usecase it’s because I’m trying to avoid a memory leak in Skulpt when returning strings/dicts from Python. If it interests you, the full story is in the bug topic here: Anvil JS - memory leak when returning data from JS, Python dicts aren't updated . It was suggested I open a separate topic only for the dict update issue.

So let’s assume for now the Javascript function is indeed necessary, and that the randomizer isn’t relevant. Rather, focus on the fact the JS function’s updates aren’t reflected in the Python dict and how to handle that, if possible.

Correct me if I’m wrong, but isn’t that whole issue about when going back and forth between JS and Python? If you just use python there’ll be no issue I think.

Yes, the behaviour is expected. When you pass a dictionary to JavaScript, JavaScript receives a plane object which is a copy of the original dictionary.

The common use case is to send a python dictionaries to external JavaScript libraries that expect plain objects.

1 Like

Thanks Stu. Guess trying to pass dicts isn’t a way to evade that memory leak :frowning: