Mojo Error: 'X' does not implement the '__eq__' method
error: 'Point' does not implement the '__eq__' method means you used an operator like == on a type that doesn’t support it. The method name in the message tells you which operator: '__eq__' is ==, '__lt__' and '__gt__' are < and >, '__add__' is +, '__iadd__' is +=. Your own structs start with none of them; you add them with a trait or a method. For the other errors in this series, see Mojo Errors Explained.
The error message
Section titled “The error message”@fieldwise_initstruct Point: var x: Int var y: Int
def main(): var p = Point(1, 2) var q = Point(1, 2) print(p == q)points.mojo:10:13: error: 'Point' does not implement the '__eq__' method print(p == q) ~ ^mojo: error: failed to parse the provided Mojo source moduleIn Mojo, p == q is shorthand for a method call, p.__eq__(q). The ^ points at the operator, and the message says the type on the left, Point, has no such method.
What it means
Section titled “What it means”Every operator maps to a special method with double underscores (a “dunder” method, the same names Python uses):
| You wrote | Method | Usual fix |
|---|---|---|
a == b, a != b |
__eq__, __ne__ |
add the Equatable trait |
a < b, a > b, a <= b, a >= b |
__lt__, __gt__, __le__, __ge__ |
add Comparable and write __lt__ |
a + b, a - b, a * b |
__add__, __sub__, __mul__ |
write the method |
a += b |
__iadd__ |
write __iadd__ (no fallback to __add__) |
In Python, == on two objects quietly compares their identity, so Point(1, 2) == Point(1, 2) is False unless you wrote __eq__. Mojo doesn’t guess. Until you say what “equal” means for your type, == doesn’t build. The operator support page of the Mojo manual lists every operator and its method.
How to fix it
Section titled “How to fix it”Fix 1: Add Equatable for == and !=
Section titled “Fix 1: Add Equatable for == and !=”If two values are equal when all their fields are equal, add the Equatable trait. Mojo writes __eq__ and __ne__ for you, field by field:
@fieldwise_initstruct Point(Equatable): var x: Int var y: Int
def main(): print(Point(1, 2) == Point(1, 2)) print(Point(1, 2) != Point(2, 1))Output:
TrueTrueIf “equal” means something else, for example two emails that differ only in upper and lower case, write def __eq__(self, other: Self) -> Bool: yourself and keep the trait. Equatable also makes in work on a List of your type; without it, p in points fails with expected 'conforms_to(T, Equatable)'. See Mojo Special Methods.
Fix 2: Add Comparable and __lt__ for ordering and sorting
Section titled “Fix 2: Add Comparable and __lt__ for ordering and sorting”For <, >, sort, min and max, write one method, __lt__ (“less than”), and add the Comparable trait. Mojo fills in >, <= and >= from it:
@fieldwise_initstruct Card(Comparable, Copyable, Writable): var rank: Int var suit: String
def __lt__(self, other: Self) -> Bool: return self.rank < other.rank
def main(): var hand: List[Card] = [Card(10, "hearts"), Card(2, "spades"), Card(7, "clubs")] sort(hand) print(hand) print(Card(10, "hearts") > Card(7, "clubs"))Output:
[Card(rank=2, suit=spades), Card(rank=7, suit=clubs), Card(rank=10, suit=hearts)]TrueWith only __lt__ and no trait, < works but > gives 'Card' does not implement the '__gt__' method. And sort(hand) without Comparable gives a long no matching function in call to 'sort' message, because sort needs a Comparable type (or a compare function). Copyable and Writable are here so the list can be sorted and printed. See Mojo Sorting & Searching.
Fix 3: Write the operator method, including __iadd__
Section titled “Fix 3: Write the operator method, including __iadd__”Arithmetic operators have no trait that writes them for you. Write the methods you need. One thing differs from Python: += does not fall back to __add__. Without __iadd__, total += Money(250) fails with 'Money' does not implement the '__iadd__' method:
@fieldwise_initstruct Money(Writable): var cents: Int
def __add__(self, other: Self) -> Self: return Self(self.cents + other.cents)
def __iadd__(mut self, other: Self): self.cents += other.cents
def main(): var total = Money(0) total += Money(250) total += Money(199) print(total, total + Money(1))Output:
Money(cents=449) Money(cents=450)__add__ returns a new value; __iadd__ changes self, so it takes mut self and returns nothing. See Mojo Operator Overloading.
Fix 4: In generic code, ask for the trait
Section titled “Fix 4: In generic code, ask for the trait”In a generic function, Mojo only knows what the bound promises. With [T: Copyable], a > b fails with 'T' does not implement the '__gt__' method. Put the trait you need into the bound:
def biggest[T: Comparable & Copyable](a: T, b: T) -> T: if a > b: return a.copy() return b.copy()
def main(): print(biggest(3, 7), biggest("pear", "apple"))Output:
7 pearComparable & Copyable means “both traits”. Now any type you pass must support >, and Mojo checks it at each call. See Mojo Generics.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- Comparing or sorting your own structs. Add
EquatableorComparable(Fixes 1 and 2). +=on a struct that only has__add__(Fix 3).Optionalvalues.a + 1witha: Optional[Int]says'Optional[Int]' does not implement the '__add__' method. The box has no math; take the value out first witha.value()ora.or_else(0). See Mojo Optional.- Generic helpers like
biggestorcontains(Fix 4).
Related errors
Section titled “Related errors”- does not conform to trait ‘Writable’: the same idea for
print. 'X' value has no attribute 'Y': a normal method (after a dot) that doesn’t exist.- value passed to ‘rhs’ cannot be converted: the method exists, but the right-hand value has the wrong type.
- All Mojo error pages: the full list.
Practice
Section titled “Practice”1. Compare versions
Section titled “1. Compare versions”Make this program build and print True then False. Two Versions are equal when both numbers match, and 1.4 is older than 1.10.
@fieldwise_initstruct Version: var major: Int var minor: Int
def main(): print(Version(1, 4) < Version(1, 10)) print(Version(1, 4) == Version(1, 10))Hint: Comparable includes Equatable, so one trait and one method are enough.
Show solution
@fieldwise_initstruct Version(Comparable): var major: Int var minor: Int
def __lt__(self, other: Self) -> Bool: if self.major != other.major: return self.major < other.major return self.minor < other.minor
def main(): print(Version(1, 4) < Version(1, 10)) print(Version(1, 4) == Version(1, 10))Output:
TrueFalse__lt__ compares the major number first, then the minor one. Comparable brings Equatable with it, so == compares both fields for you.
- The method name in the message tells you the operator:
__eq__is==,__lt__is<,__add__is+,__iadd__is+=. Equatablewrites==and!=for you, field by field.Comparableplus one__lt__gives every comparison,sort,minandmax.- Arithmetic methods you write yourself, and
+=needs its own__iadd__. - In generics, put the trait in the bound:
[T: Comparable & Copyable].
Next up: Project: Guessing Game, your first complete Mojo program, built step by step.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Add operator support to custom types: every operator and the method behind it.
- Mojo traits cheat sheet: what
Equatable,Comparableand the other traits give you. - Traits in the Mojo manual: how traits and trait bounds work.
- Mojo Special Methods: our lesson on
__eq__,__lt__,__len__and friends.