Skip to content Skip to sidebar Skip to footer

Mutable Default Method Arguments In Python

Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I am using the Python IDE PyCharm and something that is have by default is it will showing w

Solution 1:

This is the right way to do it because the same mutable object is used every time you call the same method. If the mutable object is changed afterwards, then the default value won't probably be what it was intended to be.

For example, the following code:

def status(options=[]):
    options.append('new_option')
    return options

printstatus()
printstatus()
printstatus()

will print:

['new_option']['new_option', 'new_option']['new_option', 'new_option', 'new_option']

which, as I said above, probably isn't what you're looking for.

Post a Comment for "Mutable Default Method Arguments In Python"