0

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.

hugos
  • 1,313
  • 1
  • 10
  • 19
  • 1
    *"calling those methods may have unexpected damages"* - like what? What is your objective here? – jonrsharpe Oct 17 '15 at 20:00
  • I'm using this in a decorator function so I have no clue on what the user will be doing on such methods. I don't think calling them will be a good idea. – hugos Oct 17 '15 at 20:03
  • But what does the decorator *do*? What kind of classes is it decorating? Does it need to check this when it's applied? It would be very unusual for a comparison method to change the state of its parameters. – jonrsharpe Oct 17 '15 at 20:04
  • Right now it's a decorator that verifies if the class implements a minimum set of reach comparisons, it will become something else in the future. I agree that is unusual for a comparison method to change the state of its parameters but I don't have control over it. – hugos Oct 17 '15 at 20:14
  • Have a look at how `functools.total_ordering` does it; you can check whether they're implemented directly or inherited from `object` pretty easily. – jonrsharpe Oct 17 '15 at 20:19
  • Thank you that's pretty cool. But how would I check if they were implemented directly or inherited from object? – hugos Oct 17 '15 at 20:24
  • ...in the same way that decorator does it! – jonrsharpe Oct 17 '15 at 20:24
  • Haha I'll take a look at it – hugos Oct 17 '15 at 20:25
  • They just use `dir` thanks for guiding me. – hugos Oct 17 '15 at 20:34

1 Answers1

1

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
L3viathan
  • 26,748
  • 2
  • 58
  • 81
hugos
  • 1,313
  • 1
  • 10
  • 19