Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is default variable off by one in function definition?

Tags:

python

lambda

I found an interesting issue why trying to do a the following for a code golf challenge:

>>> f=lambda s,z=len(s): 5+z
>>> f("horse")
11                            #Expected 10
>>>              
>>> def g(s,z=len(s)):
...  print "z: ", z
...  print "sum: ", 5+z
...
>>> g("horse")
z:  6
sum:  11    
>>>                       
>>> len("horse") + 5           #Expected function operation
10 

Creating the function both ways seems to initialize z as 6 instead of the expected 5, why does this happen?

like image 821
wnnmaw Avatar asked Mar 13 '23 16:03

wnnmaw


1 Answers

The python docs have a page that explains this

Python’s default arguments are evaluated once when the function is defined, not each time the function is called

In your case, s must have already been bound to a string of length 6 before you created the lambda function. When python evaluated the lambda definition with z=len(s), it evaluated to z=6. It doesn't get processed again each time you call the function.

like image 64
Brendan Abel Avatar answered Mar 25 '23 02:03

Brendan Abel