cpython icon indicating copy to clipboard operation
cpython copied to clipboard

Can dataclass ordering avoid tuple wrappers for single field comparisons?

Open rhettinger opened this issue 10 months ago • 6 comments

Proposal and Rationale

When order=True, the generated rich comparison methods wrap the target field in a tuple. This makes sense when multiple fields are being compared. However for a single field, it adds unnecessary extra work: two extra tuple allocations and deallocations, a tuple compare, and superfluous equality check on the field.

For example, the heapq docs suggest making the following class:

from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)

The generated code for less-than operation is:

 def __lt__(self,other):
  if other.__class__ is self.__class__:
   return (self.priority,)<(other.priority,)
  return NotImplemented

Instead, it would be nicer to generate:

 def __lt__(self,other):
  if other.__class__ is self.__class__:
   return self.priority<other.priority
  return NotImplemented

Behavior change

When the tuple wrapper was removed from __eq__ in favor of individual field comparisons linked by and, it resulted in faster code that matched what people would write by hand. However, it also caused issues where users had been relying on the identity checks inside the tuple comparison. That affects us here as well:

from math import nan

>>> nan <= nan
False
>>> (nan,) <= (nan,)
True

Unlike the impact of the __eq__ change, users of ordering operations are far less likely to be relying on identity-implies-equality.

One reason is that __eq__ is used with hashing but ordering operations are not. So the prior change affected dict() and set() while the proposed change does not.

Another reason is that it only affects __le__ and __ge__ but not __eq__, __ne__, __lt__, and __ge__, so it doesn't show-up 100% of the time.

Also Python's ordering tools (sorted, min, max, nsmallest, nlargest, merge, bisect, and heapq) do not use __le__ and __ge__. So they are entirely unaffected.

The upside of the behavior change is that it fixes an existing inconsistency between '<', '==', and '<=':

>>> PrioritizedItem(nan, 'x') < PrioritizedItem(nan, 'y')
False
>>> PrioritizedItem(nan, 'x') == PrioritizedItem(nan, 'y')
False 

# Inconsistent with the previous two calls
>>> PrioritizedItem(nan, 'x') <= PrioritizedItem(nan, 'y')  
True

This inconsistency is unexpected because it does not show up in hand-written code:

>>> nan < nan
False
>>> nan == nan
False
>>> nan <= nan
False

Linked PRs

  • gh-144222

rhettinger avatar Jan 23 '26 18:01 rhettinger

Hi @rhettinger, if no one is currently working on this, I’d be happy to take it on.

whyvineet avatar Jan 24 '26 13:01 whyvineet

@whyvineet Sure, go ahead and work on a PR. Just know that Eric has yet to determine whether or not this is a net win.

rhettinger avatar Jan 25 '26 02:01 rhettinger

Related preexisting PR and linked issue.

https://github.com/python/cpython/pull/137497

gesslerpd avatar Nov 10 '26 20:11 gesslerpd

There is another compatibility boundary beyond the NaN <=/>= example: equal values that support equality but not ordering. On Python 3.12.14, this currently works:

from dataclasses import dataclass

@dataclass(order=True)
class Item:
    priority: complex

a = Item(complex(1, 2))
b = Item(complex(1, 2))
print(a < b)                  # False
print(len(sorted([a, b])))    # 2
print(a.priority < b.priority)  # TypeError

The tuple comparison can resolve the equal-field case without asking complex numbers for <. The proposed direct-field expression does ask for <, so this boundary can affect __lt__ and ordering consumers such as sorted too, even though those consumers do not use __le__ or __ge__.

I verified the existing behavior and the direct-expression difference locally; I have not built the PR branch. Would it be worth including equality-only field types in the compatibility decision/test cases, or explicitly documenting that broader behavior change if the optimization is accepted?

efanntyo avatar Nov 29 '26 18:11 efanntyo

Personally I'd consider this class with an unorderable element 'broken' as it stands. Unlike tuples, dataclasses requires you to specify if you want ordering so it doesn't make a whole lot of sense to make an ordered dataclass that only contains an unorderable field.


I'd be happiest if we resolve the complete behaviour for any number of fields, rather than special casing single field classes and can close this and #137658.

I think this single field case should generalise to something close to the logic from #137497 with a slight change to return the result of the final field comparison instead of checking every field identically and then returning True/False on exhaustion. For a class with 3 fields this would look something like this:

def __le__(self, other):
    if self is other:
        return True
    if self.__class__ is other.__class__:
        if self.field1 != other.field1:
            return self.field1 <= other.field1
        if self.field2 != other.field2:
            return self.field2 <= other.field2
        return self.field3 <= other.field3
    return NotImplemented

Without the identity check __le__ would still be inconsistent with __eq__ when comparing a dataclass instance with itself with elements that compare unequal. (__eq__ will be True, __le__ will be False)

Returning the result of the final comparison is both consistent with __eq__ (see the examples that follow that use arrays) and saves one comparison in the case where the final field differs.

Comparison of 3.15 dataclasses against the different PRs and the example given in this reply for NANs, unorderable objects and arrays including `__eq__` results

Example Code:

from dataclasses import dataclass
import numpy as np

@dataclass(order=True)
class Main:
    c: object


@dataclass
class PR137497:
    # https://github.com/python/cpython/pull/137497
    c: object
    def __le__(self,other):
        if self is other:
            return True
        if other.__class__ is self.__class__:
            if self.c != other.c:
                return self.c <= other.c
            return True
        return NotImplemented


@dataclass
class PR144222:
    # https://github.com/python/cpython/pull/144222
    c: object
    def __le__(self,other):
        if other.__class__ is self.__class__:
            return self.c<=other.c
        return NotImplemented


@dataclass
class Proposed:
    c: object
    def __le__(self, other):
        if self is other:
            return True
        if self.__class__ is other.__class__:
            return self.c <= other.c
        return NotImplemented


def tryprint(s, func):
    try:
        print(s, func())
    except Exception as e:
        print(s, repr(e))


nan = float("nan")
arr = np.ones(3)
arr2 = np.ones(3) * 2

classes = (Main, PR137497, PR144222, Proposed)

print("NAN ordering, ex1 and ex2 use the same NAN object")

ex1 = Main(nan)
ex2 = Main(nan)
ex3 = Main(float("nan"))
tryprint("ex1 == ex1", lambda: ex1 == ex1)
tryprint("ex1 == ex2", lambda: ex1 == ex2)
tryprint("ex1 == ex3", lambda: ex1 == ex3)

for cls in classes:
    print(cls.__name__)

    ex1 = cls(nan)
    ex2 = cls(nan)
    ex3 = cls(float("nan"))

    tryprint("ex1 <= ex1", lambda: ex1 <= ex1)
    tryprint("ex1 <= ex2", lambda: ex1 <= ex2)
    tryprint("ex1 <= ex3", lambda: ex1 <= ex3)
print()


print("Complex ordering, ex1 and ex2 have equal value, ex3 differs")
ex1 = Main(1+2j)
ex2 = Main(1+2j)
ex3 = Main(1+3j)
tryprint("ex1 == ex1", lambda: ex1 == ex1)
tryprint("ex1 == ex2", lambda: ex1 == ex2)
tryprint("ex1 == ex3", lambda: ex1 == ex3)

for cls in classes:
    print(cls.__name__)
    ex1 = cls(1+2j)
    ex2 = cls(1+2j)
    ex3 = cls(1+3j)

    tryprint("ex1 <= ex1", lambda: ex1 <= ex1)
    tryprint("ex1 <= ex2", lambda: ex1 <= ex2)
    tryprint("ex1 <= ex3", lambda: ex1 <= ex3)
print()


print("Array ordering, ex1 and ex2 use 2*np.ones(3), ex3 np.ones(3)")
ex1 = Main(2*np.ones(3))
ex2 = Main(2*np.ones(3))
ex3 = Main(np.ones(3))
tryprint("ex1 == ex1", lambda: ex1 == ex1)
tryprint("ex1 == ex2", lambda: ex1 == ex2)
tryprint("ex1 == ex3", lambda: ex1 == ex3)

for cls in classes:
    print(cls.__name__)

    ex1 = cls(2*np.ones(3))
    ex2 = cls(2*np.ones(3))
    ex3 = cls(np.ones(3))

    tryprint("ex1 <= ex1", lambda: ex1 <= ex1)
    tryprint("ex1 <= ex2", lambda: ex1 <= ex2)
    tryprint("ex1 <= ex3", lambda: ex1 <= ex3)

Result:

NAN ordering, ex1 and ex2 use the same NAN object
ex1 == ex1 True
ex1 == ex2 False
ex1 == ex3 False
Main
ex1 <= ex1 True
ex1 <= ex2 True
ex1 <= ex3 False
PR137497
ex1 <= ex1 True
ex1 <= ex2 False
ex1 <= ex3 False
PR144222
ex1 <= ex1 False
ex1 <= ex2 False
ex1 <= ex3 False
Proposed
ex1 <= ex1 True
ex1 <= ex2 False
ex1 <= ex3 False

Complex ordering, ex1 and ex2 have equal value, ex3 differs
ex1 == ex1 True
ex1 == ex2 True
ex1 == ex3 False
Main
ex1 <= ex1 True
ex1 <= ex2 True
ex1 <= ex3 TypeError("'<=' not supported between instances of 'complex' and 'complex'")
PR137497
ex1 <= ex1 True
ex1 <= ex2 True
ex1 <= ex3 TypeError("'<=' not supported between instances of 'complex' and 'complex'")
PR144222
ex1 <= ex1 TypeError("'<=' not supported between instances of 'complex' and 'complex'")
ex1 <= ex2 TypeError("'<=' not supported between instances of 'complex' and 'complex'")
ex1 <= ex3 TypeError("'<=' not supported between instances of 'complex' and 'complex'")
Proposed
ex1 <= ex1 True
ex1 <= ex2 TypeError("'<=' not supported between instances of 'complex' and 'complex'")
ex1 <= ex3 TypeError("'<=' not supported between instances of 'complex' and 'complex'")

Array ordering, ex1 and ex2 use 2*np.ones(3), ex3 np.ones(3)
ex1 == ex1 True
ex1 == ex2 [ True  True  True]
ex1 == ex3 [False False False]
Main
ex1 <= ex1 True
ex1 <= ex2 ValueError('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()')
ex1 <= ex3 ValueError('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()')
PR137497
ex1 <= ex1 True
ex1 <= ex2 ValueError('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()')
ex1 <= ex3 ValueError('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()')
PR144222
ex1 <= ex1 [ True  True  True]
ex1 <= ex2 [ True  True  True]
ex1 <= ex3 [False False False]
Proposed
ex1 <= ex1 True
ex1 <= ex2 [ True  True  True]
ex1 <= ex3 [False False False]

DavidCEllis avatar Nov 30 '26 15:11 DavidCEllis

@DavidCEllis Agree behaviors should be generalized, if there are any changes to align the equality and order semantics.

Let me know if there's any changes needed to my PR https://github.com/python/cpython/pull/137497 based on this discussion.

Goal was to align order method semantics with current __eq__. It avoids special handling of the last field to keep all logic consistent.

gesslerpd avatar Nov 30 '26 19:11 gesslerpd