Skip to content

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.

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.

Two structs aren’t comparable with == until you say how:

@fieldwise_init
struct 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 module

The 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_init
struct 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:

True
False
True

When “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_init
struct Email(Equatable):
var address: String
def __eq__(self, other: Self) -> Bool:
return self.address.lower() == other.address.lower()
def main():
var a = Email("[email protected]")
var b = Email("[email protected]")
print(a == b)
print(a != b)

Output:

True
False

You only wrote __eq__, and != still works: Equatable provides __ne__ as “not __eq__”.

For < you write __lt__ (“less than”). On its own, it gives you < and nothing else:

@fieldwise_init
struct 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 module

Add 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_init
struct 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 False
Version(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 play
2 songs
True

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 0

The 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_init
struct Team:
var members: List[String]
def __contains__(self, name: String) -> Bool:
return name in self.members
@fieldwise_init
struct 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 False
15 30

triple is a normal struct value that remembers its factor, but triple(5) reads like a function call.

To make Int(x) and Float64(x) work on your type, write __int__ and __float__ and add the Intable and Floatable traits:

@fieldwise_init
struct 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.5

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.

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_init
struct 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.

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_init
struct 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 True

Each 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__.
  • Equatable gives you == and !=, written for you if every field supports them.
  • Write __lt__ and add Comparable to get all four comparisons, plus sort, min and max.
  • len(x) needs Sized, and Bool(x) needs Boolable, not just the method.
  • __contains__ powers in, and __call__ lets you call a value like a function.
  • Mojo ignores __str__ and __repr__; printing uses the Writable trait.

Next up: operator overloading, making +, - and * work on your own types.

Quick check

1. You wrote __len__ on your struct, but len(x) still fails. What is missing?
2. A struct has __lt__ but no traits. Which comparison works?
3. What does Equatable do for a struct whose fields are an Int and a String?
4. You define __str__ on a struct and call print(x). What happens?