Computer >> Computer tutorials >  >> Programming >> Python

How to set default parameter values to a function in Python?


Python’s handling of default parameter values is one of a few things that can bother most new Python programmers.

What causes issues is using a “mutable” object as a default value; that is, a value that can be modified in place, like a list or a dictionary.

A new list is created each time the function is called if a second argument isn’t provided, so that the EXPECTED OUTPUT is:

[12]
[43]

A new list is created once when the function is defined, and the same list is used in each successive call.

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.

What we should do

Create a new object each time the function is called, by using a default arg to signal that no argument was provided (None is often a good choice).

Example

def func(data=[]):
    data.append(1)
    return data
func()
func()
def append2(element, foo=None):
    if foo is None:
        foo = []
    foo.append(element)
    return foo
print(append2(12))
print(append2(43))

Output

[12]
[43]