tsorn
tsorn

Reputation: 3625

Pass function of function as parameter

I know how to pass a simple function as parameter to another function - but how do I pass "nested" functions? I'm trying to do something like this:

def do(func):
    print (func(6))

def a(x):
    return x*2

def b(x):
    return x*3

do(a(b))

Upvotes: 0

Views: 145

Answers (2)

TLJ
TLJ

Reputation: 4945

Using function composition approach:

def compose(f, g):
    return lambda x: f(g(x))

def do(func):
    print (func(6))

def a(x):
    return x*2

def b(x):
    return x*3

combinedAB = compose(a,b)
do(combinedAB)

Upvotes: 3

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160367

Well the main problem here is that do(a(b)) will pass the function b in the a and result in a TypeError.

The main issue here is that whatever you pass to function do has to be a callable or else the print(func(6)) statement will fail for the appropriate reasons (lack of a __call__ method) so I don't think the way this is structured fits what you're trying to do.

As a solution you could either do what @Doorknob suggested (essentially pass in a callable) or consider returning function b from function a which will then be used in function do.

So, if you change function a as so:

def do(func):
    print (func(6))

def a(x):
    x = x * 2
    def b(y):
        return x * (y * 3)
    return b

do(a(2))

You'll get a nice result of 72. Even though I'm not sure if this is strictly what you mean by "nested" functions.

Upvotes: 1

Related Questions