Mojo Special Methods
Special methods (people also call them dunder methods, for the double underscores) are methods with fixed names that Mojo calls for you. You’ve already written one: __init__, which runs when you write Point(1, 2). In the same way, a == b calls __eq__, len(x) calls __len__ and x[0] calls __getitem__. If you know Python’s special methods, the names are the same; the main difference is that some of them work best together with a trait.
What calls what
Section titled “What calls what”| You write | Mojo calls | Trait to add |
|---|---|---|
a == b, a != b |
__eq__, __ne__ |
Equatable |
a < b, a > b, a <= b, a >= b |
__lt__ and friends |
Comparable |
len(x) |
__len__ |
Sized (required) |
if x:, Bool(x) |
__bool__ |
Boolable (required for Bool(x)) |
x[i], x[i] = v |
__getitem__, __setitem__ |
none |
item in x |
__contains__ |
none |
x(5) |
__call__ |
none |
Int(x), Float64(x) |
__int__, __float__ |
Intable, Floatable |
You list traits in parentheses after the struct name: struct Version(Comparable):. Traits get their own lesson, Mojo Traits; for now, think of them as a label that says “this type supports ==” or “this type has a length”. The arithmetic operators (+, * and so on) are special methods too, and they get the next lesson.
Equality: __eq__
Section titled “Equality: __eq__”Two structs aren’t comparable with == until you say how:
@fieldwise_initstruct Point: var x: Int var y: Int
def main(): print(Point(1, 2) == Point(1, 2))hello.mojo:7:23: error: 'Point' does not implement the '__eq__' method print(Point(1, 2) == Point(1, 2)) ~~~~~~~~~~~ ^mojo: error: failed to parse the provided Mojo source moduleThe easy fix: add the Equatable trait. If every field can already be compared with ==, Mojo writes __eq__ and __ne__ for you, comparing 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)) print(Point(1, 2) != Point(2, 1))Output:
TrueFalseTrueWhen “equal” should mean something else, write __eq__ yourself. Here two email addresses count as the same if they only differ in upper and lower case:
@fieldwise_initstruct Email(Equatable): var address: String
def __eq__(self, other: Self) -> Bool: return self.address.lower() == other.address.lower()
def main(): print(a == b) print(a != b)Output:
TrueFalseYou only wrote __eq__, and != still works: Equatable provides __ne__ as “not __eq__”.
Ordering: __lt__
Section titled “Ordering: __lt__”For < you write __lt__ (“less than”). On its own, it gives you < and nothing else:
@fieldwise_initstruct Score: var points: Int
def __lt__(self, other: Self) -> Bool: return self.points < other.points
def main(): print(Score(3) < Score(5)) print(Score(3) > Score(5))hello.mojo:10:20: error: 'Score' does not implement the '__gt__' method print(Score(3) > Score(5)) ~~~~~~~~ ^mojo: error: failed to parse the provided Mojo source moduleAdd the Comparable trait and Mojo fills in >, <= and >= from your __lt__. Comparable includes Equatable, so you get == too. It also makes your type work with sort(), min() and max():
@fieldwise_initstruct Version(Comparable, Copyable, Writable): 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(): var a = Version(1, 4) var b = Version(1, 10) print(a < b, a >= b, a == b) print(max(a, b)) var all: List[Version] = [Version(2, 0), Version(1, 10), Version(1, 4)] sort(all) print(all)Output:
True False FalseVersion(major=1, minor=10)[Version(major=1, minor=4), Version(major=1, minor=10), Version(major=2, minor=0)]Version 1.10 is newer than 1.4, which a plain string comparison would get wrong. Copyable and Writable are only there so the list can be sorted and printed; Common Traits explains them.
Length and truthiness: __len__ and __bool__
Section titled “Length and truthiness: __len__ and __bool__”A struct that holds a collection usually wants len(). A struct with an “empty” state often wants to work in an if:
struct Playlist(Sized, Boolable): var songs: List[String]
def __init__(out self): self.songs = List[String]()
def add(mut self, song: String): self.songs.append(song)
def __len__(self) -> Int: return len(self.songs)
def __bool__(self) -> Bool: return len(self.songs) > 0
def main(): var p = Playlist() if not p: print("nothing to play") p.add("Blue") p.add("Yellow") print(len(p), "songs") print(Bool(p))Output:
nothing to play2 songsTrueIndexing: __getitem__ and __setitem__
Section titled “Indexing: __getitem__ and __setitem__”Square brackets call __getitem__ to read and __setitem__ to write. They can take more than one index, which is handy for a grid:
struct Grid: var cells: List[Int] var width: Int
def __init__(out self, width: Int, height: Int): self.width = width self.cells = List[Int](length=width * height, fill=0)
def __getitem__(self, row: Int, col: Int) -> Int: return self.cells[row * self.width + col]
def __setitem__(mut self, row: Int, col: Int, value: Int): self.cells[row * self.width + col] = value
def main(): var g = Grid(3, 2) g[1, 2] = 7 print(g[1, 2], g[0, 0])Output:
7 0The grid keeps its numbers in one flat List, and the two methods turn (row, col) into a position in that list. __setitem__ changes the struct, so it takes mut self; its last argument is the value on the right of =. If an index can be wrong, you can mark __getitem__ with raises and raise an error for bad input.
Membership and calling: __contains__ and __call__
Section titled “Membership and calling: __contains__ and __call__”x in thing calls thing.__contains__(x). And if a struct has __call__, you can call a value of it like a function:
@fieldwise_initstruct Team: var members: List[String]
def __contains__(self, name: String) -> Bool: return name in self.members
@fieldwise_initstruct Multiplier: var factor: Int
def __call__(self, x: Int) -> Int: return x * self.factor
def main(): var t = Team(["Ann", "Bo"]) print("Ann" in t, "Cy" in t) var triple = Multiplier(3) print(triple(5), triple(10))Output:
True False15 30triple is a normal struct value that remembers its factor, but triple(5) reads like a function call.
Converting: __int__ and __float__
Section titled “Converting: __int__ and __float__”To make Int(x) and Float64(x) work on your type, write __int__ and __float__ and add the Intable and Floatable traits:
@fieldwise_initstruct Money(Intable, Floatable): var cents: Int
def __int__(self) -> Int: return self.cents // 100
def __float__(self) -> Float64: return Float64(self.cents) / 100.0
def main(): var price = Money(1250) print(Int(price), Float64(price))Output:
12 12.5No __str__ or __repr__
Section titled “No __str__ or __repr__”In Python, __str__ decides what print(x) shows. Mojo doesn’t use __str__ or __repr__ at all: you can define a method with that name, but print and String(x) ignore it and fail with “does not conform to trait ‘Writable’”. Printing works through the Writable trait and a method called write_to, which is the topic of Printing Your Types.
The Mojo manual’s section on special methods lists the categories, and the traits cheat sheet shows which trait goes with which method.
Practice
Section titled “Practice”1. Sort some cards
Section titled “1. Sort some cards”Make a Card struct with a rank: Int and a suit: String. Make cards sort by rank, then sort this list and print it: Card(10, "hearts"), Card(2, "spades"), Card(7, "clubs").
Hint: write __lt__ and add Comparable. For sort and print on a list, the struct also needs Copyable and Writable.
Show solution
@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)Output:
[Card(rank=2, suit=spades), Card(rank=7, suit=clubs), Card(rank=10, suit=hearts)]sort only needs <, and Comparable tells it that Card has one.
2. A shopping cart
Section titled “2. A shopping cart”Make a Cart that holds a List[String] of items. Support len(cart), cart[0] and "milk" in cart, then print 2 bread True.
Hint: you need __len__ (with Sized), __getitem__ and __contains__.
Show solution
@fieldwise_initstruct Cart(Sized): var items: List[String]
def __len__(self) -> Int: return len(self.items)
def __getitem__(self, i: Int) -> String: return self.items[i]
def __contains__(self, item: String) -> Bool: return item in self.items
def main(): var cart = Cart(["bread", "milk"]) print(len(cart), cart[0], "milk" in cart)Output:
2 bread TrueEach method just passes the work on to the list inside. That’s a common pattern for small wrapper types.
- Special methods have fixed double-underscore names, and Mojo calls them for you:
==calls__eq__,len()calls__len__,[]calls__getitem__. Equatablegives you==and!=, written for you if every field supports them.- Write
__lt__and addComparableto get all four comparisons, plussort,minandmax. len(x)needsSized, andBool(x)needsBoolable, not just the method.__contains__powersin, and__call__lets you call a value like a function.- Mojo ignores
__str__and__repr__; printing uses theWritabletrait.
Next up: operator overloading, making +, - and * work on your own types.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo structs: special methods: the manual’s overview of dunder methods.
- Add operator support to custom types: a full walkthrough with comparison, subscript and Boolean methods.
- Mojo traits cheat sheet: each standard trait with the method it needs and what it gives you.
Comparable: the trait’s methods and which ones have default versions.