2016-05-25 22 views
4

如何在python中重新定義語法級別lambda運算符?如何在Python中重寫'lambda'?

例如,我希望能夠做到這一點:

λ = lambda 
squared = λ x: x*x 
+0

只是好奇,你爲什麼要這麼做? –

+1

我想創建一個數學外觀的Python只是出於美學原因。我喜歡這個Vim插件:https://github.com/ehamberg/vim-cute-python,但想看看我是否可以進一步。 – therealtypon

+3

你可以在你的文本編輯器中做到這一點,但不是在Python本身,因爲它是一個關鍵字。 –

回答

1

至於其他一些用戶已經注意到,lambda是Python中的保留字,所以不能被混淆或以同樣的方式覆蓋該你可以在不改變Python語言的語法的情況下使用函數或變量。但是,您可以使用exec關鍵字定義一個函數,它自己定義並從字符串表達式中返回一個新的lambda函數。這在一定程度上改變了樣式,但頂級行爲是相似的。

即:

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)) 

這相當於:

# Returns the square of x. 
y = lambda x : x ** 2 

# Prints 2^2 = 4. 
print(y(2))