Wraps around lambda expressions

I have functions in python that take two inputs, do some manipulations and return two outputs. I would like to change the output options, so I wrote a wrapper function around the original function that creates a new function with a new output order

def rotate(f):
    h = lambda x,y: -f(x,y)[1], f(x,y)[0]
    return h

f = lambda x, y: (-y, x)
h = rotate(f)

However, this results in an error message:

NameError: global name 'x' is not defined

x is an argument for a lambda expression, so why define it?

The expected behavior is what hshould be a new function that is identicallambda x,y: (-x,-y)

+3
source share
2 answers

You need to add parentheses around the lambda expression:

h = lambda x,y: (-f(x,y)[1], f(x,y)[0])

Otherwise, Python interprets the code as:

h = (lambda x,y: -f(x,y)[1]), f(x,y)[0]

and his a 2-tuple.

+7

. :

def rotate(f):
    h = lambda x,y: (-f(x,y)[1], f(x,y)[0])
    return h
+5

Source: https://habr.com/ru/post/1762557/


All Articles