What it looks like you're trying to do is create functions with pre-assigned values for i
, j
, k
, andw
. That is, you don't want to pass those values in, you want the function to know them already, and for them to be different based on which exact function you call.
There is almost no point to this, you're almost always better off just calling the function and passing in the values, but it can be done.
First we'll need a function that makes the desired function and "bakes in" the predefined variables. Since you're new to Python I won't go into the details of why, I'll just point out that we need it. (You could also use functools.partial
or default argument values.)
def make_make_feature(i, j, k, w):
def make_feature(imagemat):
# do whatever make_feature does
# using imagemat, i, j, k, and w
return make_feature
What we have here is a function, make_make_feature()
, that takes the four arguments, and returns a function (make_feature()
) that takes a single argument and can use the variables as they were passed to the "maker" function. imgmat
must be passed to the constructed function when it is later called but it already knows the other four values.
Now we have the nested loops that define the functions. We'll store them in a dictionary; the key will be a tuple of the four arguments.
make_feature_funcs = {}
for i in range(1, 64):
for j in range (1, 64):
for h in range(1, 65 - i):
for w in range(1, (65 - j) / 2):
make_feature_funcs[i, j, k, w] = make_make_feature(i, j, k, w)
Now we have the dictionary make_feature_funcs
. So, make_feature_funcs[1, 2, 3, 4]
is the function that has the values 1, 2, 3, and 4 baked in for the variables i, j, k, and w. We can then call that function and pass in imgmat
:
make_feature_funcs[1, 2, 3, 4](imgmat)
As you can see this is no clearer than just calling make_feature()
directly and passing in the variables you want.
One (minor) advantage is that you can only use the pre-defined values for i, j, k, and w, but you could also just add code to the function to validate the values if that's your goal. Which is why I said that there's almost no point in doing it.