How should functions be tested for equality or identity?

前端 未结 4 2048
眼角桃花
眼角桃花 2020-12-04 19:54

I would like to be able to test whether two callable objects are the same or not. I would prefer identity semantics (using the \"is\" operator), but I\'ve discovered that wh

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 20:31

    While I don't have answers to all of your questions, I suspect the trick is to use __func__ for callables that have it (i.e. for methods):

    In [32]: def same_func(func1, func2):
       ....:     if hasattr(func1, '__func__'):
       ....:         func1 = func1.__func__
       ....:     if hasattr(func2, '__func__'):
       ....:         func2 = func2.__func__
       ....:     return func1 is func2
       ....: 
    
    In [33]: same_func(b, foo.bar)
    Out[33]: True
    
    In [34]: same_func(f, fun)
    Out[34]: True
    
    In [35]: same_func(foo.met, fun)
    Out[35]: True
    
    In [36]: same_func(c, foo.can)
    Out[36]: True
    

提交回复
热议问题