Updating default arguments in Python across calls -
this question has answer here:
in following function l stores values during every call.
for example, if call f(1)
, l [1]
. when call again previous l appended new value. l [1,1]
.
def f(a, l=[]): l.append(a) return l
but in function:
i = 5 def f(arg=i): print arg = 6
no matter how many times call function, argument still 5
- not remain updated between calls.
what reason why not updated list does?
this question. reason why happens because default arguments functions stored single objects in memory, not recreated every time call function.
so when have list []
default argument, there 1 list forever duration of program. when add list adding 1 copy of list. still true numbers 5
. however, numbers immutable in python, , when alter default argument starts @ number, you're making point new number , not editing 5
object, whereas many operations on lists mutate list in place rather returning new list.
http://docs.python.org/3/tutorial/controlflow.html#default-argument-values
important warning: default value evaluated once. makes difference when default mutable object such list, dictionary, or instances of classes.
the recommended solution, if need behaviour of empty list default argument without having same empty list default argument every call function, this:
def f(a, l = none): if l none: l = [] l.append(a) return l
the creation of empty list evaluated on individual calls function - not once.
Comments
Post a Comment