How can I test whether a variable holds a lambda?

前端 未结 5 1517
灰色年华
灰色年华 2021-02-04 00:19

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(my         


        
5条回答
  •  故里飘歌
    2021-02-04 01:16

    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__ == ""
    

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

提交回复
热议问题