Default arguments in Python

Note: This post is pretty much only of interest (and will only make sense) to programmers.

I’ve been using Python a lot for around 6 months now, and just yesterday I run into an apparently common gotcha. I’ve boiled it down to a very basic example.

First, let’s define a simple function with a default argument:

def f( a = [] ):
    a.append(1)
    print a

Now, let’s call it twice and see what happens:

> f()
[1]
> f()
[1, 1]

Probably not what you expected? From the POV of a C programmer, this just means that Python default arguments map to something like:

    static int a[] = {};

rather than:

    int a[] = {};

at the start of a function. (For those whom may not know; yes, C allows for static variables nested within functions.)

2 thoughts on “Default arguments in Python”

Comments are closed.