4
我正在處理一個包含多個模塊的項目。簡化問題,有一些變量x。有時它可能是int或float或list。但它可能是一個lambda函數,應該以不同的方式處理。如何檢查變量x是lambda?如何檢查該變量是拉姆達函數
例如
>>> x = 3
>>> type(x)
<type 'int'>
>>> type(x) is int
True
>>> x = 3.4
>>> type(x)
<type 'float'>
>>> type(x) is float
True
>>> x = lambda d:d*d
>>> type(x)
<type 'function'>
>>> type(x) is lambda
File "<stdin>", line 1
type(x) is lambda
^
SyntaxError: invalid syntax
>>> type(x) is function
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>>
'isinstance(x,types.LambdaType)'看起來更習慣。 – bereal
值得注意的是'types.LambdaType'是'types.FunctionType'的別名。沒有(簡單或可靠的)方法來區分lambda函數和用'def'創建的函數。 – Blckknght
@Blckknght這就是爲什麼我們需要檢查'__name__' :-) – thefourtheye