Passing Objects between PyScript and JavaScript

PyScript is a framework that allows for Python to run in html. It’s supposed to be able to pass objects between regular JS and PyScript, except it doesn’t seem to be working for me.

PyScript Documentation: How to Pass Objects from PyScript to Javascript (and Vice Versa) — PyScript documentation
Repl: https://replit.com/@arn5891/FrustratedGameDev#index.html

<py-script>
    wth=100
    ht=100
  </py-script>
  
  <script >
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var pimg = document.getElementById("pimg");
    var wth = pyscript.interpreter.globals.get("wth");
    var ht = pyscript.interpreter.globals.get("ht");
    console.log(wth);
  </script>

Hey @arn5891, maybe try using JavaScript’s eval() as shown in the docs:

<py-script>
    from js import createObject
    from pyodide.ffi import create_proxy
    createObject(create_proxy(globals()), "pyodideGlobals")

    wth = 100
    ht = 100
</py-script>

<script>
    function createObject(object, variableName) {
        // Bind a variable whose name is the string variableName
        // to the object called 'object'
        let execString = variableName + " = object"
        console.log("Running '" + execString + "'");
        eval(execString)
    }

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var pimg = document.getElementById("pimg");
    var wth = pyodideGlobals.get("wth");
    var ht = pyodideGlobals.get("ht");
    console.log(wth);
</script>
2 Likes

I already tried that method, and I copy/pasted your attempt- it shows that the function is running, but when I try to print the value of the object wth, it doesn’t do anything.

1 Like

Sorry for inconveniencing you, I overlooked some info from the docs.

Since PyScript tags evaluate after all JavaScript on the page, we can’t just dump a console.log(...) into a <script> tag, since that tag will evaluate before any PyScript has a chance to. We need to delay accessing the Python variable in JavaScript until after the Python code has a chance to run. The following example uses a button … to achieve this"

This works out quite well, considering my game needs a start button. If you have the the admin level to close this topic, it’d be appreciated, else I’ll just mark your answer as a solution.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.