Constructing JS Objects

The PyScript (Pyodide) and PyScript(Micropython) version of this recipe are identical,

Python lacks the new operator that JavaScript uses to construct new objects. To work around this, proxies of JavaScript classes within Python gain a new() which calls their constructor.

If you have a JavaScript class defined like so:

var Boat = class Boat{
    constructor(size, power){
        this.size = size
        this.power = power

We can construct new instances of the class within Python like so:

from js import Boat

sailboat ="33ft", "sailpower")
tugboat ="80ft", "diesel")

print(f"{sailboat.size=}, {tugboat.power=}")

This also works for classes already defined in the JavaScript global scope. For example, to create a new JavaScript Float64Array (an array of 8-byte floats), you can use the following similar syntax:

from js import Float64Array

my_array =[1,2,3,4])

print(f"{my_array.byteLength= }")