Can you please someone describe the behavior of Python optional arguments in functions?
My understanding was that the optional arguments use the default value in the function definition.
The following code has correct behavior.
# Function
def testf2(val=0):
val += 5
print(val)
val=0
return
# Testing
testf2()
testf2(10)
testf2()
# Output:
5
15
5
But I have no idea why the similar code with the optional list has completely different behavior. The function remembers some data even when the list is cleared by the val=[].
# Function
def testf(val=[]):
val.append("OK")
print(val)
val=[]
return
# Testing
testf()
testf(["myString"])
testf()
testf(["mySecondString"])
testf()
# Output:
['OK'] #excpected ['OK']
['myString', 'OK'] #excpected ['myString']
['OK', 'OK'] #excpected ['OK']
['mySecondString', 'OK'] #excpected ['mySecondString']
['OK', 'OK', 'OK'] #excpected ['OK']
Many thanks for your help.