tags:

views:

85

answers:

3

I'm writing a function in Python that takes another function as an argument. Something like this:

DoStuffToFunction(myFunction, arg1, arg2, arg3)

However, I want to construct myFunction based on the return of another function

MakeFunction(arg1, arg2, arg3).

So I do something like:

def MakeFunction(arg1, arg2, arg3):
    def retFunction(arg1, arg2):
        return arg3
    return retFunction

But then, how do I get myFunction from MakeFunction? If I do myFunction = MakeFunction(stuff1, stuff2, stuff3) I get an error. If I call DoStuffToFunction(MakeFunction, etc1, etc2, etc3) I can't define the parameters of MakeFunction.

The idea is that DoStuffToFunction takes a function. This function is a function of two variables that returns some mathematical result of those two variables. For example: def someFunction(x, z): return x*z

And MakeFunction should let you quickly create these functions without needing to spend time defining the functions. Basically, it's an attempt to let the user use DoStuffToFunction without much programming knowledge or the know-how to make the function needed.

I feel like I'm missing something here, and if anyone could tell me what it is (or just tell me what I should be Googling) I'd appreciate it!

Update: Wow, okay I think I realized what my problem is. I was attempting to use variables that had never been created and expected Python to know what I wanted it to do. It looks like I need to look into tokenizing strings if I want to do what it is that I intended. Thanks guys!

A: 

DoStuffToFunction(MakeFunction(stuff1,stuff2,stuff3),etc1,etc2,etc3) should work.

On the other hand, you may be having difficulty with accidentally creating closures, which may be causing unexpected effects on the second and subsequent calls.

jkerian
+1  A: 
>>> def MakeFunction(arg1, arg2, arg3):
    def retFunction(arg1, arg2):
        return arg3+arg2
    return retFunction

>>> fun = MakeFunction(1, 2, 3)
>>> fun(4, 12)
15

I don't see any errors.

Klark
A: 

But then, how do I get myFunction from MakeFunction? If I do myFunction = MakeFunction(stuff1, stuff2, stuff3) I get an error

what error do you get? it works fine in here:

def MakeFunction(arg1, arg2, arg3):
    def retFunction(arg1, arg2):
        return arg3+arg2
    return retFunction

myFunction = MakeFunction('stuff1', 'stuff2', 'stuff3')

def DoStuffToFunction(func, arg1, arg2, arg3):
    pass

DoStuffToFunction(myFunction, 'arg1', 'arg2', 'arg3')
Lie Ryan