Skip to content

Add .new Method to JavaScript Clases #171

Open
@wiwichips

Description

@wiwichips

Describe your feature request here.

Class.new

Feature Request: add a new static method to classes exposed to Python to instantiate JavaScript classes.
Code example:

import pythonmonkey as pm
JsDateClass = pm.Date

myDate = JsDateClass.new(0) # in JS this would look like: myDate = new JsDateClass(0);

Relevant Context

Unlike JavaScript, Python doesn't use the new keyword (or anything like it) for instantiating classes. For example:

class SomeClass:
    pass
obj = SomeClass()

However, JavaScript "classes" may require the new keyword to properly setup the object. ES6 classes will throw an error if not instantiated with new.

So we needed to provide a way for Python to instantiate JavaScript classes and chose to add a new function to the PythonMonkey api which returns a function wrapper for the constructor function which can be used to instantiate the class as if it were called with new. See the relevant ticket here: #144

This topic was debated in the TC39 forums here: https://es.discourse.group/t/function-prototype-new/1772 ; however, the community does not appear to be very unified on this subject. @WebReflection suggested adding Class.new to the JS spec

Pyodide uses Class.new to solve this, refer to the Pyodide documentation here: https://pyodide.org/en/stable/usage/api/python-api/ffi.html#pyodide.ffi.JsProxy.new

  • PythonMonkey should have a similar API spec to Pyodide
  • These products will likely be used together for instance with PythonMonkey on the server and Pyodide in the browser

Code example

import pythonmonkey as pm

myDate = pm.Date.new(0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions