Dead simple, just nest your functions:
def make_multiplier(x):
def multiplier(y):
return x * y
return multiplier
Nested functions automatically look up unknown variables (x in this case) from their surrounding scope, using the value of x as it was when the outer function was called. The thing to remember here is that functions are just objects too, you can store them in a variable just like you can with other python objects, and defer calling them.
This gives:
>>> def make_multiplier(x):
... def multiplier(y):
... return x * y
... return multiplier
...
>>> f = make_multiplier(10)
>>> f(1)
10
>>> f(2)
20
>>> g = make_multiplier(5)
>>> g(1)
5
>>> f(3)
30
Note how g was given a different value for x, which is independent from the value for x in f.
You could use a lambda as well; lambdas are just anonymous functions limited to one expression; that's enough here:
def make_multiplier(x):
return lambda y: x * y
Another alternative technique is binding x to a keyword parameter, which means you could override it if you so wish:
def make_multiplier(x):
def multiply(y, x=x):
return x * y
return multiply
or the lambda version:
def make_multiplier(x):
return lambda y, x=x: x * y
and then pass in one or two arguments to the returned callable:
>>> f = make_multiplier(10)
>>> f(5)
50
>>> f(5, 3)
15