Late-binding of function defaults (was Re: What is a function parameter =[] for?)

Steven D'Aprano steve at pearwood.info
Thu Nov 19 19:33:36 EST 2015


On Fri, 20 Nov 2015 07:57 am, Marko Rauhamaa wrote:

> Laura Creighton <lac at openend.se>:
> 
>> My experience says that the people who are confused want lists to
>> behave like tuples. period. i.e. they don't want lists to be mutable.
> 
> I think it's simpler than that. When you have:
> 
>    def f(x=[]):
>        y = []
> 
> the first [] is evaluated when "def" is executed, while the latter [] is
> evaluated whenever "f" is executed. It's easy to be confused.

It shouldn't be. The function declaration 

    def f(x=[]):

is executed only once. The function body, conveniently indented to make it
stand out:

        y = []

is executed every time you call the function. 


[Aside: that nice clean design is somewhat muddied by docstrings. Despite
being indented, docstrings are actually part of the declaration in the
sense that they are handled only once, at function definition time.]


-- 
Steven




More information about the Python-list mailing list