therealtypon
therealtypon

Reputation: 485

How to override 'lambda' in Python?

How can I redefine the syntax level lambda operator in python?

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

λ = lambda
squared = λ x: x*x

Upvotes: 5

Views: 1009

Answers (1)

Erick Shepherd
Erick Shepherd

Reputation: 1443

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. However, you can define a function which itself defines and returns a new lambda function from a string expression using the exec keyword. 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)) 

Upvotes: 3

Related Questions