News for hackers. Stuff that matters.
Re:Python quirks by rbanffy on Friday July 12, 2013 @03:46PM (#6034747)
In other words, defaults are static (an in C) and initialized when the function is defined, not when it's called.
Re:Python quirks by adamtj on Friday July 12, 2013 @10:40PM (#6036477)
It is perhaps more correct to say "when the function is instantiated". Functions in python aren't exactly "defined". Functions are objects same as everything else. The "def" keyword is how you call the constructor for a function object. The kwarg default values are evaluated once at object construction time and saved.

The "def" statement may construct different distinct function objects from a single definition. Each distinct function object has different default value objects, but each function object reuses its own default value objects each time it's called.

Consider this:

    def outer_fn():
        def inner_fn(foo={}):
            # The id() function returns an internal
            # object identifier.  Different objects 
            # have different ids.
            print id(foo)
        return inner_fn
    
    inner_fn_1 = outer_fn()
    inner_fn_2 = outer_fn()
    inner_fn_1()
    inner_fn_1()
    inner_fn_2()
    inner_fn_2()
Re:Python quirks by rbanffy on Saturday July 13, 2013 @04:13AM (#6037021)
You are absolutely correct, of course. I was using a C-ism.