# Potential bug on interacts using lists

Hello, Sage Community! While trying to solve this question, I have identified a potential bug. Consider the following code:

def test(xL=[]):
xL.append(1)
return xL

@interact
def _(x=slider(0,10,1,1)):
f = test()
show(f)


This is a MWE of the problem presented in the question I mentioned. For what I understand, this code should show an slide, and print , no matter where the slider is positioned. However, the actual behavior is that it indeed shows  the first time the code is executed, but then, every time I move the slider, the list grows appending one more 1.

Even though the default value for xL in the first subroutine (test()) is xL = [], and I am calling it with no arguments, it seems that the previous value of xL (corresponding to the previous position of the slider) is passed every time the slider is moved. In particular, if I execute this code and move the slider three times, I get the output

[1, 1, 1, 1]


On the other hand, if I specifically pass the empty list [] to test(), like in

f = test([])


then, the result is always .

Can somebody confirm and explain this? Is this a bug?

edit retag close merge delete

Sort by » oldest newest most voted It is not really a SageMath problem, but a Python one. I do not know why xL is not the empty list each time that test() is called, according to the default value of xL in your definition of test. However, this happens even if such a default value is not an empty list, as you can check with any Python interpreter:

>>> def test(xL=):
...     xL.append(len(xL))
...     return xL
...
>>> for i in range(3):
...     print(test())
...
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]


However, if one uses concatenation instead of the append method, one gets the expected behaviour:

>>> def test(xL=):
...     return xL + [len(xL)]
...
>>> for i in range(3):
...     print(test())
...
[0, 1]
[0, 1]
[0, 1]

more

2