Common mistakes we make in Python and why we should avoid that part 3

Posted by Afsal on 31-Aug-2021

Hi Pythonistas!

This is part 3 of the series. If you are new, please click on part 1 and part 2 to check out the previous parts of the series.

Today we are going to discuss a very simple mistake that can cause big trouble. It is using mutable variables as the default argument to a function.

Let  us consider the below example.

def mutable_test_function(first, second=[]):
    second.extend(first)
    return second
mutable_test_function([1,2,3], [1,2,3])

Out[63]: [1, 2, 3, 1, 2, 3]

In [64]: mutable_test_function([1,2,3])

Out[64]: [1, 2, 3]

In [65]: mutable_test_function([1,2,3])

Out[65]: [1, 2, 3, 1, 2, 3]

In [66]: mutable_test_function([1,2,3])

Out[66]: [1, 2, 3, 1, 2, 3, 1, 2, 3]

If we pass both the arguments, this function will behave properly. For the first time, when we pass only one argument the function works properly. But when we call the function again with the one argument, we can see that output is the aggregate of the previous and current input. If we call the argument multiple times, the output will grow.

Reason:

In Python, the default argument is evaluated only once. If it is a mutable argument its output will keep updating each time this function is called.

What is the solution:

The solution for this is to use an immutable argument as the default argument. If we want to mutate the data, create a variables inside the function. See the below example.

def mutable_test_function(first, second=None):
    if second is None:
        second = []
        second.extend(first)
    return second
In [74]: mutable_test_function([1,2,3])

Out[74]: [1, 2, 3]

In [75]: mutable_test_function([1,2,3])

Out[75]: [1, 2, 3]

In [76]: mutable_test_function([1,2,3])

Out[76]: [1, 2, 3]

Hope you learned from this article. happy Coding !!

Previous post links

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that-part-2/

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that/