TranscryptOrg / Transcrypt

Python 3.9 to JavaScript compiler - Lean, fast, open!
https://www.transcrypt.org
Apache License 2.0
2.82k stars 215 forks source link

`dict`'s `pop()` method fails to remove `None`-valued item #827

Open phfaist opened 1 year ago

phfaist commented 1 year ago

There appears to be a bug in the runtime's implementation of the pop() method of dict objects. If the value in the dictionary associated with the given key happens to be None (null), then the value is not returned and it is not removed from the dictionary. I think the fix is very easy (see below).

Here's a minimal working example:

# bug.py
a = { 'hello': None }
value = a.pop('hello', '<DEFAULT>')
print('value = ', value, '; a = ', a)

The outputs I get with python, and with transcrypt/node, are:

# python bug.py
value =  None ; a =  {}

# transcrypt bug.py --nomin ; echo '{"type":"module"}' >__target__/package.json; node __target__/bug.js
value =  <DEFAULT> ; a =  {'hello': None}

It appears that the incorrect behavior is the result of a comparison of the value with undefined using the != operator in the runtime's implementation of __pop__(). Correct behavior is achieved if I modify the runtime's __pop__ function in __target__/org.transcrypt.__runtime__.js as follows:

function __pop__ (aKey, aDefault) {
    var result = this [aKey];
-    if (result != undefined) {
+    if (result !== undefined) {
        delete this [aKey];
        return result;
    } else {
        if ( aDefault === undefined ) {
            throw KeyError (aKey, new Error());
        }
    }
    return aDefault;
}

Then I obtain, correctly:

# node __target__/bug.js
value =  None ; a =  {}

From searching in transcrypt's code base, it would appear that the relevant line to update is this one.