Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I have another problem with ==. I have some code that needs to know if two (nested) tuples of Any are equivalent. I'd like to test (tupleA == tupleB), but that doesn't work if NaN appears anywhere in tuples because (NaN != NaN).

This is because == is an overloaded concept. Python has chosen to define == in the way that makes the most mathematical sense in the case of NaN.

Maybe there's a metaprogramming way to override how == in interpreted for floats?

  with float_equality_test( math.isclose):
    assert (0.1 + 0.2) == 0.3

  # This still allows (+0.0 == -0.0):
  def my_float_eq( a :float, b :float) ->bool:
    return (math.isnan( a) and math.isnan( b)) or (a == b)
  with float_equality_test( my_float_eq):
    assert (1, 2.0, math.nan) == (1, 2.0, math.nan)


If you use your own dataclasses (from dataclassy) instead of tuples, you can override this behaviour.

Making NaNs compare unequal to themselves was a hack that dates back from the time modern floats were first introduced.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: