Search code examples
pythonnew-style-class

How to verify if class implements a rich comparison method?


With the old style classes simply using hasattr works:

>>> class old:
...     pass
...
>>> hasattr(old, '__eq__')
False

Using the new style classes every class has the attribute __eq__:

>>> class nsc(object):
...     pass
...
>>> hasattr(nsc, '__eq__')
True

This is the expected behaviour as hasattr(object, '__eq__') also returns True. This is true for every rich comparison method.

How to verify if class implements a rich comparison method if I can't use hasattr? One thing that comes to mind is to call the method and see if it raises a NotImplemented exception. But calling those methods may have unexpected damages.


Solution

  • You can do it by using dir instead of hasattr. Rich comparison methods don't appear in the list returned by the dir function.

    >>> class nsc(object):
    ...     pass
    ...
    >>> '__eq__' in dir(nsc)
    False