Search code examples
javascriptpythonscope

PyMiniRacer adding Python classes to JS scope


Using PyMiniRacer, I would be able to use Python objects in Javascript; using the PyV8 library:

import PyV8

class Scope(PyV8.JsClass):
    def __init__(self):
        self.obj1 = Object1()
        self.obj2 = Object2()

pythonScope = Scope()
context     = PyV8.JsContext(pythonScope)
context.enter()
context.eval(...)

And using this code, the javascript can access the properties of Scope: obj1 and obj2

For PyMiniRacer, looking at the code, the MiniRacer class doesn't appear to accept any arguments into the constructor, so I don't see how I could add a Python Scope class into the JS scope. Is there a specific way of defining the class to be able to add a set of python classes to the JS scope, or do I need to inject them into the JS scope using a method I have missed while looking over the source code?

In the Ruby RubyRacer, (I understand that the RubyRacer and PyMiniRacer are individual projects by different authors, although PyMiniRacer is inspired by RubyRacer) objects in the Ruby scope can be embedded by calling context["funcName"] = funcName], but in Python...

>>> from py_mini_racer import py_mini_racer
>>> context = py_mini_racer.MiniRacer()
>>> def helloWorld(num):
        return num * 2

>>> context["helloWorld"] = helloWorld
Traceback (most recent call last):
    File "<pyshell#5>", line 1, in <module>
        context["helloWorld"] = helloWorld
TypeError: 'MiniRacer' object does not support item assignment
>>> 

...it raises an error. I also tried context.__dict__["helloWorld"] = "helloWorld", and running context.eval(helloWorld(5)) returns a ReferenceError: helloWorld is not defined error. All it does is allow me to call context.helloWorld(5) which doesn't help in executing from JS.

How can I insert Python objects into the JS scope such that in the JS code, I can call and access the methods and attributes from the Python object?


Solution

  • Unfortunately, PyMiniRacer does not support attaching Python objects or functions to a JavaScript Context so it is not possible to call Python code from the JavaScript code.