scripts: Added __hash__ to CsvFrac, tweaked __eq__

This adds __hash__ to CsvFrac, and tweakes __eq__ to be more strict
about equality.

Previously CsvFrac only considered the relevant ratio for equality,
making hashing difficult:

- before: 1/2 == 2/4 => true
- after:  1/2 == 2/4 => false

But now that we have csv.py, with the explicit ratio function, it's
probably a good idea to be strict by default.

Note comparison is unchanged:

- 1/2 < 2/4 => false
- 1/2 > 2/3 => false

---

This popped up during debugging, and would be useful to have around.

Note CsvInt/CsvFloat already implicitly define __hash__ through
namedtuple's implicit __eq__ and friends. But this is disabled in
CsvFrac due to the explicit __eq__.

Which is good because otherwise it would've been wrong with the ratio
comparison!
This commit is contained in:
Christopher Haster
2026-02-05 14:01:41 -06:00
parent ebde2c7063
commit 73e06612bf
2 changed files with 8 additions and 6 deletions
+4 -3
View File
@@ -227,10 +227,11 @@ class CsvFrac(co.namedtuple('CsvFrac', 'a,b')):
def __mod__(self, other):
return self.__class__(self.a % other.a, self.b % other.b)
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
self_a, self_b = self if self.b.a else (CsvInt(1), CsvInt(1))
other_a, other_b = other if other.b.a else (CsvInt(1), CsvInt(1))
return self_a * other_b == other_a * self_b
return super().__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
+4 -3
View File
@@ -357,10 +357,11 @@ class CsvFrac(co.namedtuple('CsvFrac', 'a,b')):
def __mod__(self, other):
return self.__class__(self.a % other.a, self.b % other.b)
def __hash__(self):
return super().__hash__()
def __eq__(self, other):
self_a, self_b = self if self.b.a else (CsvInt(1), CsvInt(1))
other_a, other_b = other if other.b.a else (CsvInt(1), CsvInt(1))
return self_a * other_b == other_a * self_b
return super().__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)