开发者

Wrappers around lambda expressions

开发者 https://www.devze.com 2023-01-14 03:06 出处:网络
I have functions in python that take two inputs, d开发者_JAVA百科o some manipulations, and return two outputs. I would like to rearrange the output arguments, so I wrote a wrapper function around the

I have functions in python that take two inputs, d开发者_JAVA百科o some manipulations, and return two outputs. I would like to rearrange the output arguments, so I wrote a wrapper function around the original function that creates a new function with the 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 is giving an error message:

NameError: global name 'x' is not defined

x is an argument to a lambda expression, so why does it have to be defined?

The expected behavior is that h should be a new function that is identical to lambda x,y: (-x,-y)


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 h is a 2-tuple.


There is problem with precedence. Just use additional parentheses:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号