Skip to content

Commit 4c0fb36

Browse files
committed
make the comparison methods compare individually to match eq
1 parent 72a37bc commit 4c0fb36

3 files changed

Lines changed: 26 additions & 4 deletions

File tree

docs/code_examples/outputs/docs_ex08_converters.output

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
ConverterEx(unconverted='42', converted=42)
22
Source:
33
def __eq__(self, other):
4+
if self is other:
5+
return True
46
return (
57
self.unconverted == other.unconverted
68
and self.converted == other.converted

docs/code_examples/outputs/docs_ex09_annotated.output

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ Slots: {'x': None, 'a': None, 'b': None, 'c': None, 'd': None, 'e': None, 'f': N
1515

1616
Source:
1717
def __eq__(self, other):
18+
if self is other:
19+
return True
1820
return (
1921
self.x == other.x
2022
and self.a == other.a

src/ducktools/classbuilder/__init__.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,8 @@ def eq_generator(cls, funcname="__eq__"):
486486
# fmt: off
487487
code = (
488488
f"def {funcname}(self, other):\n"
489+
f" if self is other:\n"
490+
f" return True\n"
489491
f" return (\n"
490492
f" {instance_comparison}\n"
491493
f" ) if {class_comparison} else NotImplemented\n"
@@ -497,20 +499,36 @@ def eq_generator(cls, funcname="__eq__"):
497499

498500

499501
def get_order_generator(cls, funcname, *, operator):
502+
class_comparison = "self.__class__ is other.__class__"
500503
field_names = [
501504
name
502505
for name, attrib in get_fields(cls).items()
503506
if attrib.compare
504507
]
505508

506-
self_tuple = ", ".join(f"self.{name}" for name in field_names)
507-
other_tuple = self_tuple.replace("self.", "other.")
509+
# Equal objects should be False for gt/lt comparisons
510+
eq_return = "True" if "=" in operator else "False"
511+
512+
instance_comparisons = [
513+
(
514+
f" if self.{name} != other.{name}:\n"
515+
f" return self.{name} {operator} other.{name}\n"
516+
)
517+
for name in field_names
518+
]
519+
instance_comparisons.append(
520+
f" return {eq_return}"
521+
)
522+
523+
instance_comparison = "".join(instance_comparisons)
508524

509525
# fmt: off
510526
code = (
511527
f"def {funcname}(self, other):\n"
512-
f" if self.__class__ is other.__class__:\n"
513-
f" return ({self_tuple}) {operator} ({other_tuple})\n"
528+
f" if self is other:\n"
529+
f" return {eq_return}\n"
530+
f" if {class_comparison}:\n"
531+
f"{instance_comparison}\n"
514532
f" return NotImplemented\n"
515533
)
516534
# fmt: on

0 commit comments

Comments
 (0)