Skip to content

Commit

Permalink
Fix AttributeError in Point.__eq__.
Browse files Browse the repository at this point in the history
The other type this is compared to might not be Point, and that
shouldn't raise an error. It's often a programming mistake to write that
comparison, but there's a way to run into this without the caller having
a bug: comparing two instances of a dataclass with an `Point | None`
member where the rhs has None and the lhs has a Point.
  • Loading branch information
DanAlbert committed Dec 1, 2023
1 parent c65e497 commit 05ebda0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions dcs/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ def __truediv__(self, other: float) -> Point:
return self * (1 / other)

def __eq__(self, other):
if not isinstance(other, Point):
return False
return self.x == other.x and self.y == other.y

def __ne__(self, other: object) -> bool:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ def test_latlng(self) -> None:
self.assertAlmostEqual(p2.x, 0)
self.assertAlmostEqual(p2.y, 0)

def test_point_eq(self) -> None:
terrain = Caucasus()
self.assertEqual(Point(0, 0, terrain), Point(0, 0, terrain))
self.assertNotEqual(Point(0, 0, terrain), Point(0, 1, terrain))
self.assertNotEqual(Point(0, 0, terrain), Point(1, 0, terrain))
self.assertNotEqual(Point(0, 0, terrain), None)


class RectangleTests(unittest.TestCase):
def test_rectangle(self) -> None:
Expand Down

0 comments on commit 05ebda0

Please sign in to comment.