language design - "Least Astonishment" in Python: The Mutable Default Argument -
anyone tinkering python long plenty has been bitten (or torn pieces) next issue:
def foo(a=[]): a.append(5) homecoming
python novices expect function homecoming 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 1 time 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 reply (to myself) next question: reason binding default argument @ function definition, , not @ function execution? uncertainty experienced behavior has practical utilize (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" ... homecoming [] ... >>> >>> def b(x=a()): ... x.append(5) ... print x ... executed >>> b() [5] >>> b() [5, 5]
to me, seems design decision relative set scope of parameters: within function or "together" it?
doing binding within function mean x
bound specified default when function called, not defined, nowadays 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 beingness evaluated on definition; default parameters kind of "member data" , hence state may alter 1 phone call other - in other object.
in case, effbot has nice explanation of reasons behavior in default parameter values in python. found clear, , suggest reading improve knowledge of how function objects work.
python language-design least-astonishment
No comments:
Post a Comment