Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a bound method is the same as unbound

Tags:

python

class

I want to check (in my tests) that a method of object is the same as a method of a given class.

class Cls:
    def foo(self):
        pass

obj = Cls()
assert obj.foo == Cls.foo  # assert will fail

Which operation can be used instead of obj.foo == Cls.foo to produce True if the bound method is the same as unbound (except for 'boundness')?

like image 972
George Shuklin Avatar asked Dec 23 '22 22:12

George Shuklin


2 Answers

On Python 2.7.x :

>>> Cls.foo.__func__ is obj.foo.__func__
True
like image 132
bruno desthuilliers Avatar answered Dec 28 '22 06:12

bruno desthuilliers


In Python 3:

>>> class Cls:
...     def foo(self):
...         pass
... 
>>> obj = Cls()
>>> obj.foo
<bound method Cls.foo of <__main__.Cls object at 0x101d8f588>>
>>> dir(obj.foo)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> obj.foo.__func__
<function Cls.foo at 0x101d92400>
>>> obj.foo.__func__ is Cls.foo
True

Looking through the dir() of an object is an easy way to explore and look for potentially useful attributes.

like image 33
Alex Hall Avatar answered Dec 28 '22 06:12

Alex Hall