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.)

No related posts.

2 thoughts on “Default arguments in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">