Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test whether a variable holds a lambda?

People also ask

Can Lambda contain if?

Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.

What is Lambda variable?

An environment variable is a pair of strings that is stored in a function's version-specific configuration. The Lambda runtime makes environment variables available to your code and sets additional environment variables that contain information about the function and invocation request.

Which is a valid type for this lambda function?

A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You can pass values from the current scope to a lambda expression. The RemoveHandler statement is an exception.

Can Lambda take only one input?

Note that the function can only take one iterable as the input.


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


def isalambda(v):
  LAMBDA = lambda:0
  return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__

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.


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)