pyotherside icon indicating copy to clipboard operation
pyotherside copied to clipboard

Support conversion of JS Boolean variables to Python bool

Open mattaustin opened this issue 11 years ago • 6 comments

I have a problem where a JavaScript variable with a boolean value is not being passed to the Python function correctly, and I end up with an empty Python dict.

qmlexperiment.py contains:

def pyfoo(bar):
    print('python - bar is: {0}'.format(bar))

qml contains:

import QtQuick 2.0
import io.thp.pyotherside 1.2

Python {

    onError: {
        console.log('python error: ' + traceback);
    }

    function foo() {
      importModule('qmlexperiment', function() {
            var bar = new Boolean(true);
            print('qml - bar is: ' + bar);
            call('qmlexperiment.pyfoo', [bar], function(result) {});
        });
    }

}

output:

qml - bar is: true
python - bar is: {}

Am I doing something wrong, or should the function be being passed a Python boolean?

If bar is replaced with true in the call args, then the Python function is correctly passed in 'True':

qml - bar is: true
python - bar is: True

mattaustin avatar Jun 02 '14 11:06 mattaustin

The translator doesn't handle Boolean objects, just the true/false constants.

BTW: why would you use Boolean(true)?

zyga avatar Jun 02 '14 11:06 zyga

Just simplifying with Boolean(true) for the example (my actual code is generating the boolean from another var, and wanted to make sure I had a pure boolean object for the translator). The docs say the data type mapping should work both ways: http://pyotherside.readthedocs.org/en/latest/#data-type-mapping

mattaustin avatar Jun 02 '14 11:06 mattaustin

It does but apparently the javascript engine doesn't treat new Boolean() as a boolean

zyga avatar Jun 02 '14 12:06 zyga

Specifically it seems that instead of QVariant with bool you get some other (I don't know javascript engine types to be sure) type.

zyga avatar Jun 02 '14 12:06 zyga

Indeed - thank you for your help!

I've replaced:

var bar = new Boolean(baz);

with:

var bar = baz ? true : false;

and all is well!

mattaustin avatar Jun 02 '14 12:06 mattaustin

While in general, you should use true and false, it might make sense that we also support Boolean objects and convert them to a boolean value on the Python side:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

Reopening. Maybe we can get around to implement that at some point.

thp avatar Jun 02 '14 12:06 thp