def myfunc(n):
return lambda a: a * n
mydoubler = myfunc(2)
mydoubler(5)
The first part of this defines a function which returns lambda a: a * n
:
def myfunc(n):
return lambda a: a * n
Lambdas are anonymous functions that can be useful in situations such as the ones Science done right
outlines, as well as others. They can be difficult for people to follow, though. (I'm a fan, but I do try to think about their effect on readability for others.)
If you run myfunc(2)
without assigning its return value anywhere, you get this:
<function __main__.myfunc.<locals>.<lambda>(a)>
This is partially evaluated; by calling myfunc(2)
, you are setting the value of n
in the function to 2
, but the value of the lambda
function's variable a
remains unset.
You can assign this partially-evaluated function to a name, like so:
mydoubler = myfunc(2)
Then, you can call the name you just defined like a function, passing it a value that will be assigned to a
from the original definition:
mydoubler(5) # returns 10
mydoubler(11) # returns 22