Got bitten by Python’s default parameters?

Python’s default parameters are very convenient to use. Python programmers usually get bitten (once) with the fact that in Python functions are first-class objects and default parameters are kind of “member data”. So this would happen:

def foo(a=[]):
    return a
>>> foo()
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]

The detailed explanation of why this is happening could be found here and here.

But just keep in mind that the best way to not fall in to it, would be:

def myfunc(value=None):
    if value is None:
        value = []

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s