Mutable Default Arguments (A Common Python Bug)

One of the most common mistakes Python developers make is using mutable objects as default function arguments.

In this following example, the default list items=[] is used as the function argument. When mutable object - list is used as function argument, the object is created once and reused every time the function is called.

This creates hidden persistent storage, where data keeps accumulating across calls.

def add_items(item, items=[]):

    items.append(item)

    return items

print(add_items(1))

print(add_items(2))

Output

[1]

[1, 2]

"Mutable objects should not be used as default function arguments. Instead, use None and create the object inside the function."

In this way, each function call now creates a fresh new list.

def add_items(item, items=None):

    if items is None:

        items = []

    items.append(item)

    return items

print(add_items(1))

print(add_items(2))

Output

[1]

[2]



Comments

Popular posts from this blog

What Is a Design Pattern and Why Should We Use It?

Distributed Version Control System - Part 1

Distributed Version Control System - Part 2