[英]How to override 'lambda' in Python?
How can I redefine the syntax level lambda
operator in python? 如何在python中重新定义语法级
lambda
运算符?
For example, I want to be able to do this: 例如,我希望能够这样做:
λ = lambda
squared = λ x: x*x
As some other users have noted, lambda
is a reserved keyword in Python, and so cannot be aliased or overridden in the same way that you would a function or variable without changing the grammar of the Python language. 正如其他一些用户所指出的那样,
lambda
是Python中的保留关键字,因此不能以与函数或变量相同的方式别名或覆盖,而不改变Python语言的语法。 However, you can define a function which itself defines and returns a new lambda function from a string expression using the exec
keyword. 但是,您可以使用
exec
关键字定义一个函数,该函数本身定义并从字符串表达式返回一个新的lambda函数。 This changes the styling somewhat, but the top level behavior is similar. 这会稍微改变样式,但顶级行为是类似的。
That is: 那是:
def λ(expression):
local_dictionary = locals()
exec("new_lambda = lambda %s" % (expression), globals(), local_dictionary)
return local_dictionary["new_lambda"]
# Returns the square of x.
y = λ("x : x ** 2")
# Prints 2 ^ 2 = 4.
print(y(2))
Which is comparable to: 这与以下内容相当:
# Returns the square of x.
y = lambda x : x ** 2
# Prints 2 ^ 2 = 4.
print(y(2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.