Description
Mutable default arguments appear to behave differently in Transcrypt compared with CPython.
In Python, default argument expressions are evaluated when the function definition is executed. Therefore, when a mutable object such as [] is used as a default argument, calls that omit the argument use the same object.
In Transcrypt 3.9.5, the default list appears to be recreated for every function call instead.
Minimal example
Tested with Python 3.9 and Transcrypt 3.9.5:
def append_list1(new_item, lst=[]):
lst.append(new_item)
return lst
print(append_list1(1), append_list1(2))
def append_list2(new_item, lst=[]):
lst.append(new_item)
return lst
lst1 = append_list2(1)
lst2 = append_list2(2)
print(lst1 is lst2)
CPython output
Output when running the Transcrypt-generated JavaScript
Expected behaviour
The default value of lst should be created once when the function is defined. Therefore, calls to append_list2() without explicitly supplying lst should receive the same list object, and lst1 is lst2 should be True.
Generated JavaScript
The generated JavaScript appears to initialise the default argument inside the function when the argument is omitted, conceptually equivalent to:
var append_list2 = function (new_item, lst) {
if (typeof lst == 'undefined') {
var lst = [];
}
lst.append(new_item);
return lst;
};
This causes a new list to be created each time the function is called without lst, rather than once when the function is defined.
Environment
Python: 3.9.0
Transcrypt: 3.9.5
Node.js: v24.19.0
OS: Windows 11
Description
Mutable default arguments appear to behave differently in Transcrypt compared with CPython.
In Python, default argument expressions are evaluated when the function definition is executed. Therefore, when a mutable object such as
[]is used as a default argument, calls that omit the argument use the same object.In Transcrypt 3.9.5, the default list appears to be recreated for every function call instead.
Minimal example
Tested with Python 3.9 and Transcrypt 3.9.5:
CPython output
Output when running the Transcrypt-generated JavaScript
Expected behaviour
The default value of
lstshould be created once when the function is defined. Therefore, calls toappend_list2()without explicitly supplyinglstshould receive the same list object, andlst1 is lst2should beTrue.Generated JavaScript
The generated JavaScript appears to initialise the default argument inside the function when the argument is omitted, conceptually equivalent to:
This causes a new list to be created each time the function is called without
lst, rather than once when the function is defined.Environment
Python: 3.9.0
Transcrypt: 3.9.5
Node.js: v24.19.0
OS: Windows 11