python - "Least Astonishment" and the Mutable Default Argument -


anyone tinkering python long enough has been bitten (or torn pieces) following issue:

def foo(a=[]):     a.append(5)     return 

python novices expect function return list 1 element: [5]. result instead different, , astonishing (for novice):

>>> foo() [5] >>> foo() [5, 5] >>> foo() [5, 5, 5] >>> foo() [5, 5, 5, 5] >>> foo() 

a manager of mine once had first encounter feature, , called "a dramatic design flaw" of language. replied behavior had underlying explanation, , indeed puzzling , unexpected if don't understand internals. however, not able answer (to myself) following question: reason binding default argument @ function definition, , not @ function execution? doubt experienced behavior has practical use (who used static variables in c, without breeding bugs?)

edit:

baczek made interesting example. of comments , utaal's in particular, elaborated further:

>>> def a(): ...     print("a executed") ...     return [] ...  >>>             >>> def b(x=a()): ...     x.append(5) ...     print(x) ...  executed >>> b() [5] >>> b() [5, 5] 

to me, seems design decision relative put scope of parameters: inside function or "together" it?

doing binding inside function mean x bound specified default when function called, not defined, present deep flaw: def line "hybrid" in sense part of binding (of function object) happen @ definition, , part (assignment of default parameters) @ function invocation time.

the actual behavior more consistent: of line gets evaluated when line executed, meaning @ function definition.

actually, not design flaw, , not because of internals, or performance.
comes fact functions in python first-class objects, , not piece of code.

as think way, makes sense: function object being evaluated on definition; default parameters kind of "member data" , therefore state may change 1 call other - in other object.

in case, effbot has nice explanation of reasons behavior in default parameter values in python.
found clear, , suggest reading better knowledge of how function objects work.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -