diff --git a/docs/changelog.md b/docs/changelog.md index 56093362b..9ded91d72 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -34,6 +34,7 @@ ### Fixed - getattr and dir on JsProxy now report consistent results and include all names defined on the Python dictionary backing JsProxy. [#1017](https://github.com/iodide-project/pyodide/pull/1017) +- `JsProxy.__bool__` now produces more consistent results: both `bool(window)` and `bool(zero-arg-callback)` were `False` but now are `True`. Conversely, `bool(empty_js_set)` and `bool(empty_js_map)` were `True` but now are `False`. [#1061](https://github.com/iodide-project/pyodide/pull/1061) ## Version 0.16.1 *December 25, 2020* diff --git a/src/core/hiwire.c b/src/core/hiwire.c index 6451da2c7..fb647b5f3 100644 --- a/src/core/hiwire.c +++ b/src/core/hiwire.c @@ -346,7 +346,17 @@ EM_JS_NUM(int, hiwire_get_length, (JsRef idobj), { EM_JS_NUM(bool, hiwire_get_bool, (JsRef idobj), { var val = Module.hiwire.get_value(idobj); // clang-format off - return (val && (val.length === undefined || val.length)) ? 1 : 0; + if (!val) { + return false; + } + if (val.size === 0) { + // I think things with a size are all container types. + return false; + } + if (Array.isArray(val) && val.length === 0) { + return false; + } + return true; // clang-format on }); @@ -376,8 +386,10 @@ EM_JS_REF(char*, hiwire_constructor_name, (JsRef idobj), { MAKE_OPERATOR(less_than, <); MAKE_OPERATOR(less_than_equal, <=); -MAKE_OPERATOR(equal, ==); -MAKE_OPERATOR(not_equal, !=); +// clang-format off +MAKE_OPERATOR(equal, ===); +MAKE_OPERATOR(not_equal, !==); +// clang-format on MAKE_OPERATOR(greater_than, >); MAKE_OPERATOR(greater_than_equal, >=); diff --git a/src/tests/test_typeconversions.py b/src/tests/test_typeconversions.py index 64d256213..cd045d01a 100644 --- a/src/tests/test_typeconversions.py +++ b/src/tests/test_typeconversions.py @@ -128,6 +128,27 @@ def test_js2python(selenium): ) +def test_js2python_bool(selenium): + selenium.run_js( + """ + window.f = ()=>{} + window.m0 = new Map(); + window.m1 = new Map([[0, 1]]); + window.s0 = new Set(); + window.s1 = new Set([0]); + """ + ) + assert ( + selenium.run( + """ + from js import window, f, m0, m1, s0, s1 + [bool(x) for x in [f, m0, m1, s0, s1]] + """ + ) + == [True, False, True, False, True] + ) + + @pytest.mark.parametrize("wasm_heap", (False, True)) @pytest.mark.parametrize( "jstype, pytype",