convert Javascript object to Python object

433 views
Skip to first unread message

Matej Buzáš

unread,
Feb 8, 2019, 3:22:02 PM2/8/19
to Skulpt
Hello,

is possible to convert javascript object to Python object? Function Sk.ffi.remapToPy(obj) creates dictionary, but I need object.
For instance:

Let's say I have part of code in Javascript like this:

var Event = function(x,y) {
           this.x = x;
           this.y = y;
       };

and then somewhere in the code I return this:


var obj = new Event(e.x, e.y);
return Sk.ffi.remapToPy(obj);

I expect it creates python object, and after I call 

print(inst.x)

it would return the value of x, but it doesn't work. It works only when I call 

print(inst['x'])

because Sk.ffi.remapToPy converts it to dict.

Thank you

Björn T

unread,
Feb 9, 2019, 2:03:15 AM2/9/19
to Skulpt
I didn't work with remaptopy.

I would generate a module and import it like metioned here:http://skulpt.github.io/skulpt/using.html

Sk.externalLibraries = {
    numpy
: {
        path
: 'http://example.com/static/primeronoo/skulpt/external/numpy/__init__.js',
        dependencies
: ['/static/primeronoo/skulpt/external/deps/math.js'],
}
};

Björn T

unread,
Feb 9, 2019, 2:15:44 AM2/9/19
to Skulpt
var $builtinmodule = function(name)
{
 
var mod = {};
 
 
var myalert = function(s) {
  alert
(s);
 
}
 mod
.alert = new Sk.builtin.func(function(a) {
 
return myalert(a.v);
 
});


 mod
.Actor = Sk.misceval.buildClass(mod, function($gbl, $loc) {
  $loc
.__init__ = new Sk.builtin.func(function(self) {
   
self.x = 0;
 
});

  $loc
.__getattr__ = new Sk.builtin.func(function (self, name) {
   
if (name != null && (Sk.builtin.checkString(name) || typeof name === "string")) {
   
var _name = name;
   
if (Sk.builtin.checkString(name)) {
     _name
= Sk.ffi.remapToJs(name);
   
}
   
switch (_name) {
     
case 'x':
       
return self.x;
   
}
   
}
 
});

  $loc
.__setattr__ = new Sk.builtin.func(function (self, name, value) {
   
if (name != null && (Sk.builtin.checkString(name) || typeof name === "string")) {
   
var _name = name;
   
if (Sk.builtin.checkString(name)) {
     _name
= Sk.ffi.remapToJs(name);
   
}
   
switch (_name) {
     
case 'x':
     
self.x = value;
     
return;
   
}
   
}
 
});
 
   $loc
.getx = new Sk.builtin.func(function(self) {
   
return self.x;
   
});
 
},
 
'Actor', []);
 
return mod;



This is an example module called Actor that worked for me. I am sorry for the indentation.

Matej Buzáš

unread,
Feb 9, 2019, 3:51:12 AM2/9/19
to Skulpt
Thank you very much. Is it possible to create instance of this class directly in Javascript?
I have some problems with that, especially when I try to send parameter to constructor, it invokes Sk.builtin.TypeError.

Thank tou 
 

Björn T

unread,
Feb 9, 2019, 5:12:41 AM2/9/19
to Skulpt
I am sorry, I don't know.
You can probably append your python code with initilisation before passing it to skulpt.
Reply all
Reply to author
Forward
0 new messages