Skip to content

Importing Python Objects in JavaScript

It may be useful for some applications to extract objects from Python via JavaScript.

Once PyScript has been loaded, we can extract objects from its global scope. If we have objects in the Python global scope:

my_string = "Hello again"  

We can retrieve a reference to this Python object by name using pyscript.interpreter.globals.get(name):

<button onclick="console.log(pyscript.interpreter.globals.get('my_string'))">Click Me</button>

Once Pyodide has been loaded, we can extract objects from its global scope. If we have objects in the Python global scope, we can extract them in JavaScript using pyodide.globals.get(...):

async function main() {
    let pyodide = await loadPyodide();
    // Pyodide is now ready to use...
    console.log(pyodide.runPython(`
        my_string = "Hello again"
    `));

    const s = pyodide.globals.get('my_string')
    console.log(s) #logs hello again
};
main();