How to override 'lambda' in Python?

How can I override the syntax operator lambdain python?

For example, I want to be able to do this:

λ = lambda
squared = λ x: x*x
+4
source share
1 answer

As some other users have noted, it lambdais a reserved keyword in Python and therefore cannot be an alias or overridden just as if you were using a function or variable without changing the grammar of the Python language. However, you can define a function that itself defines and returns a new lambda function from a string expression using the keyword exec. This changes the style a bit, but the top-level behavior is similar.

I.e:

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)) 
+1
source

All Articles