Seems to me, this is a good case for using partial from the functools module.
So say I have a function that takes an input, squares it and adds some variable to it before returning the result:
def x_squared_plus_n(x,n):
return (x**2)+n
If I want to curry, or redefine that function, modifying it so that a fixed number (say 5) is always squared, and has a number n added to it, I can do so by using partial
from functools import partial
five_squared_plus_n = partial(x_squared_plus_n,5)
Now, I have a new function five_squared_plus_n
for which the first x parameter in the original function's parameter signature is fixed to x=5. The new function has a parameter signature containing only the remaining parameters, here n
.
So calling:
five_squared_plus_n(15)
or equivalently,
five_squared_plus_n(n=15)
The answer of 40
is returned.
Any combination of parameters can be fixed like this and the resulting "curried" function be assigned to a new function name. It's a very powerful tool.
In your example, you could wrap your partial calls in a loop, over which the values of different values could be fixed, and assign the resultant functions to values in a dictionary. Using my simple example, that might look something like:
func_dict = {}
for k in range(1,5):
func_dict[k]=partial(x_squared_plus_n,k)
Which would prepare a series of functions, callable by reference to that dictionary - so:
func_dict[1](5)
Would return 12+5=6 , while
func_dict[3](12)
Would return 32+12=21 .
It is possible to assign proper python names to these functions, but that's probably for a different question - here, just imagine that the dictionary hosts a series of functions, accessible by key. I've used a numeric key, but you could assign strings or other values to help access the function you've prepared in this way.
Python's support for Haskell-style "functional" programming is fairly strong - you just need to dig around a little to access the appropriate hooks. I think,m subjectively, there's perhaps less purity in terms of functional design, but for most practical purposes, there is a functional solution.