Transcrypt icon indicating copy to clipboard operation
Transcrypt copied to clipboard

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

Open phfaist opened this issue 3 years ago • 1 comments

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.

phfaist avatar Sep 18 '22 14:09 phfaist

Will be fixed in v3.9.4

I know this was opened a long time ago, but thank you @phfaist for providing a clean example and fix. I also found an issue with dict.popitem() popping from the front of the list instead of the back like CPython and fixed that while I was in there as well.

JennaSys avatar Jul 28 '24 07:07 JennaSys