How can I test whether a variable holds a lambda?

Question:

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))
Asked By: ralfoide

||

Answers:

mylambda.func_name == '<lambda>'
Answered By: Ming-Tang
def isalambda(v):
  LAMBDA = lambda:0
  return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
Answered By: Alex Martelli

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 *.

ATTENTION to the reader: this is wrong! types.LambdaType is types.FunctionType, so the above exrpession will match both Lambdas and Functions, alike.

Answered By: dbg

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 I’d use:

callable(mylambda) and mylambda.__name__ == "<lambda>"

(This answer is relevant to Python2.7.5, onwards.)

Answered By: Augusta

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)
Answered By: user3238121
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.