tags:

views:

67

answers:

2

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 can write this, but it feels clumsy:

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

mylambda.func_name == '<lambda>'

SHiNKiROU
Isn't that a bit fragile?
ralfoide
Yes, this isn't something specified by the language and it might break at any time. Don't do it.
Glenn Maynard
+1  A: 
def isalambda(v):
  return isinstance(v, type(lambda: None)) and v.__name__ == '<lambda>'
Alex Martelli
Thanks, I'll go for that. Just testing the type as I did is not ideal since any function will match so checking ___name___ or func_name is a good combo on top of that. Dunno how likely it is that the internal lambda name changes later though. It's still quite clumsy :-)
ralfoide
@ralfoids, agreed on clumsiness, but then Python `lambda`s _are_ totally clumsy all the way;-) BTW, what difference does it make to you whether a var is a `def`'d function or `lambda`, anyway?
Alex Martelli
@ralfoide, You could use `v.__name__== (lambda: None).__name__` if you are worried about the name of `lambda` changing
gnibbler
@Alex and @glenn above: funny I end up writing my testing checking whether it's a function, and indeed decided not to care whether it's a lambda or a function. Still it was interesting to see it's possible to test for and I like @gnibbler's idea to not depend on a constant.
ralfoide
@gnibbler: A Python implementation could, in principle, give lambdas unique names, eg. based on co_filename/co_firstlineno, or use a placeholder name that's also a valid function name (eg. simply "lambda"). Maybe not ideal, but valid--better off avoiding tricks.
Glenn Maynard
@alex, maybe exactly same difference as in Lisp, even the implementation is not clean: None ( or NIL :) (COMMENT 'FOR 'LISPERS)
Tony Veijalainen