How can I test whether a variable holds a lambda?

2020-05-25 00:55发布

Is there a way to test whether a variable holds a lambda? The context is I'd like to check a type in a unit test:

self.assertEquals(lambda, type(myVar))

The type seems to be "function" but I didn't see any obvious builtin type to match it. Obviously, I could write this, but it feels clumsy:

self.assertEquals(type(lambda m: m), type(myVar))

5条回答
Rolldiameter
2楼-- · 2020-05-25 01:34
def isalambda(v):
  LAMBDA = lambda:0
  return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
查看更多
一夜七次
3楼-- · 2020-05-25 01:38
mylambda.func_name == '<lambda>'
查看更多
祖国的老花朵
4楼-- · 2020-05-25 01:44

There is no need to do any hacks, the built in inspect module handles it for you.

import inspect
print inspect.isfunction(lambda x:x)
查看更多
Anthone
5楼-- · 2020-05-25 01:57

Use the types module:

from types import *

assert isinstance(lambda m: m, LambdaType)

According to the docs, It is safe to use from types import *.

查看更多
Juvenile、少年°
6楼-- · 2020-05-25 01:58

This is years past-due, but callable(mylambda) will return True for any callable function or method, lambdas included. hasattr(mylambda, '__call__') does the same thing but is much less elegant.

If you need to know if something is absolutely exclusively a lambda, then mylambda.__name__ == "<lambda>" is what I'd use.

(This answer is relevant to Python2.7.5.)

查看更多
登录 后发表回答