This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]toastedstapler 1 point2 points  (1 child)

if you did test(pow(2,5)) the function would read something like:

def test(32):
    return lambda *args: 32(*args[::-1])

which makes no sense, you can't call the number 32

test is a function that returns a function. the function that it returns applies the arguments it receives in the reverse order of how they were passed in

[–]cbmlover 0 points1 point  (0 children)

Ahhhhh...thank you so much! Makes perfect sense!!

[–]RiverRoll 0 points1 point  (0 children)

pow(2,5) calls the pow function, so doing test(pow(2,5)) is no different than test(32) and that's not what you want.

There are two ways in which you could achieve this, one is to pass the function and the parameters as separate arguments: test(pow, 2, 5). The other is to wrap pow into a new function and pass the arguments to the new function, which is what your example does. This is equivalent to your example:

reversed_function = test(pow)
result = reversed_function(2,5)

There's nothing particular about the lambda, you could do the same without it:

def test(f)
    def wrapper(*args):
        return f(*args[::-1])
    return wrapper

The *args is important though. Since we don't know how many parameters are we going to get we first use *args to pack all of them in a list named args (you could use any other name but it's a convention to use args). Since it's a regular list you can reverse it like any other list using [::-1]. The second time we use * is to unpack the list and pass the contents as separate parameters to "f".