Problem:
I am trying to transfer a list from python, x = [1,2,3,4], to an array in javascript with the same values, x = [1,2,3,4]. I want to use pyscript to do this.
I have tried using the following –> pyscript.interpreter.globals.get(‘x’)
I can get this to work with simple values, x = 42. However when transferring a list, it packages it into a proxy object. I can’t seem to unpackage it into a useful array in javascript. Console.log and inner.HTML calls show the whole value of x, but I can’t iterate through the object, and I can’t pull single values, such as x[2], which should return the value, 3.
Things I’ve tried:
I’ve tried using import js, and labeling the item as js.x to transport the list to javascript, but I still run into the whole proxy-object problem.
I’ve tried looking this up on stack overflow but couldn’t find any similar questions. I tried looking up how to unpackage the proxy object, but I couldn’t find any relevant information or instructions.
Question:
How can I unpackage this proxy object?
Here’s my code
<html>
<head>
<title>Table Editor</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<py-script>x = [1,2,3,4]</py-script>
<button onclick="show_x_in_console()">show 'x' from Python in console.log</button>
<button onclick="show_x_in_body()">show 'x' from Python in body</button>
<script>
function show_x_in_console(){
console.log(`In Python right now, x = ${pyscript.interpreter.globals.get('x')}`)
}
function show_x_in_body(){
var id1 = document.getElementById("id1")
var id2 = document.getElementById("id2")
var id3 = document.getElementById("id3")
var x = pyscript.interpreter.globals.get('x')
id1.innerHTML = x
id2.innerHTML = typeof(x)
id3.innerHTML = x[2]
}
</script>
<p id="id1"></p>
<p id="id2"></p>
<p id="id3"></p>
</body>
</html>
This is what the page looks like. When I click the second button, it shows x[2] as undefined instead of 3.
2
Answers
I see that the problem you’re facing is because the way Python’s list is being passed to JavaScript is not directly usable. You need to convert it to a JavaScript array before you can access its elements like you normally would in JavaScript. So you should change it to
Array.from()
.Here is the updated function:
Try it and let me now the results! 🙂
You can use spread syntax to convert the Proxy to an array:
Alternatively, use
.get
instead of bracket notation to access an element of the list by index: