0

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.

1 Answers1

1

Python’s default arguments are evaluated once when the function is defined, not each time the function is called. This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

The Hitchhiker's Guide to Python: Common Gotchas

Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39