Menu

The Python Default Argument Bug That Looks Completely Normal
📰

The Python Default Argument Bug That Looks Completely Normal

DEV Community: beginners·Krishna·15 days ago
#XbUJqGgv
#devtobeginners#devto#dev#list#tags
Reading 0:00
15s threshold

Here's a Python function that looks completely normal:

def add_tag ( tag , tags = []): tags . append ( tag ) return tags

Enter fullscreen mode

Exit fullscreen mode

Give it a tag and, optionally, an existing list of tags.

If you don't pass a list, it looks like the function should start with an empty one.

Right?

Let's try it.

print ( add_tag ( " urgent " )) print ( add_tag ( " billing " )) print ( add_tag ( " refund " ))

Enter fullscreen mode

Exit fullscreen mode

Output:

['urgent'] ['urgent', 'billing'] ['urgent', 'billing', 'refund']

Enter fullscreen mode

Exit fullscreen mode

Wait. What?

Each call was supposed to start with an empty list. Instead, every call remembers the tags from the previous ones.

The function isn't broken.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.