Boom100100
Boom100100

Reputation: 117

How to differentiate between lambda and def functions?

Is there way to do a type comparison for lambdas and def functions? I expect False to be output via some procedure, but I don't know if that level of granularity is native to python functions. My use case is making sure that a function registered to an event is not a lambda so it can be unregisterable later via another method.

def foo():
    pass

(lambda: None).__class__ == foo.__class__ # >> True

Edit: my use case is actually more educational than functional, so I'm really just concerned with ways of distinguishing lambda functions from def functions.

Upvotes: 2

Views: 290

Answers (2)

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

Lambdas can be identified by their __name__ field, whose value will initially be <lambda>, whereas a def function will have its real name in this field.

def foo():
    pass

bar = lambda: None

print(foo.__name__) # foo
print(bar.__name__) # bar

But, do note that I can "trick" this. There's nothing stopping me from giving a lambda a name.

baz = lambda: None
baz.__name__ = "Hah! Gotcha!"

print(baz.__name__) # Hah! Gotcha!

Upvotes: 1

Barmar
Barmar

Reputation: 780974

You can check the function's name. A lambda will be named <lambda>.

def islambda(f):
    return f.__name__ == '<lambda>'

def foo():
    pass

print(islambda(lambda: None)) # True
print(islambda(foo)) # false

Upvotes: 7

Related Questions