Mojo Error: type 'X' does not conform to trait 'Writable'
error: invalid call to 'print': an element of 'values' with type 'Point' does not conform to trait 'Writable'; either prove the conformance with 'conforms_to', or add conformance means you tried to print a value that Mojo doesn’t know how to turn into text. It happens the first time you print your own struct, a list of your structs, None, or a value of a generic type T. Most of the time the fix is one word: add Writable to the struct. 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(3, 4) print(p)point.mojo:9:11: error: invalid call to 'print': an element of 'values' with type 'Point' does not conform to trait 'Writable'; either prove the conformance with 'conforms_to', or add conformance print(p) ~~~~~ ^Imported from point.mojo:1:Mojo/stdlib/std/io/io.mojo:359:1: note: function declared heredef print[*Ts: Writable](*values: *Ts.values, *, sep: StringSpan = " ", end: StringSpan = "\n", flush: Bool = False, var file: RawFileDescriptor = stdout) # note - synthetic signature^mojo: error: failed to parse the provided Mojo source modulePiece by piece:
an element of 'values':valuesis the name ofprint’s arguments (all the things you pass it). One of them is the problem.with type 'Point': that’s the one, yourPoint.does not conform to trait 'Writable':printonly accepts types that have theWritabletrait. You can see that in the note:print[*Ts: Writable].either prove the conformance with 'conforms_to', or add conformance: the second half, “add conformance”, is the fix you almost always want.conforms_tois for advanced generic code.
What it means
Section titled “What it means”A trait is a set of abilities a type promises to have. Writable is the ability to write itself out as text. Int, String, Float64, Bool, List[Int], Dict and Optional[Int] all have it. A struct you write only has the traits you list after its name.
Python prints any object, but for your own classes the default looks like <__main__.Point object at 0x7f...>, which is rarely what you want. Mojo asks you to opt in instead. The traits page of the Mojo manual explains traits in general.
How to fix it
Section titled “How to fix it”Fix 1: Add Writable to the struct
Section titled “Fix 1: Add Writable to the struct”Put Writable in parentheses after the struct name. If every field is printable, Mojo writes the text for you:
@fieldwise_initstruct Point(Writable): var x: Int var y: Int
def main(): var p = Point(3, 4) print(p) print("Start:", p)Output:
Point(x=3, y=4)Start: Point(x=3, y=4)That’s often all you need while you’re learning or debugging. If a field’s own type isn’t Writable, you get a different message, Could not derive Writable for Item - member field ... does not implement Writable. Add Writable to that type too.
Fix 2: Choose your own format with write_to
Section titled “Fix 2: Choose your own format with write_to”For output that users see, write a write_to method. print, t-strings and String(...) all use it:
@fieldwise_initstruct Point(Writable): var x: Int var y: Int
def write_to(self, mut writer: Some[Writer]): writer.write("(", self.x, ", ", self.y, ")")
def main(): var p = Point(3, 4) print(p) print(t"Moved to {p}")Output:
(3, 4)Moved to (3, 4)writer.write(...) takes any number of printable values, like print does. The Mojo Printing Your Types lesson goes further, with t-strings inside write_to and nested types. Note that __str__ and __repr__ from Python do nothing in Mojo; write_to is the method that counts.
Fix 3: Print the fields instead
Section titled “Fix 3: Print the fields instead”If you only need a quick look and don’t want to change the struct, print its fields. They’re plain Ints, which are already printable:
@fieldwise_initstruct Point: var x: Int var y: Int
def main(): var p = Point(3, 4) print("Point:", p.x, p.y)Output:
Point: 3 4Fix 4: In generic code, require Writable
Section titled “Fix 4: In generic code, require Writable”In a generic function, Mojo only knows what the trait bound promises. def show[T: Copyable](x: T): print(x) fails with type 'T' does not conform to trait 'Writable', because a Copyable type might not be printable. Ask for Writable in the bound:
def show[T: Writable](x: T): print("value:", x)
def main(): show(5) show("hi")Output:
value: 5value: hiNow every type you pass must be printable, and Mojo checks that at each call. See Mojo Generics and Mojo Traits.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- Your first struct. Add
Writable(Fix 1). - A list of your structs.
print(points)with aList[Point]saystype 'List[Point]' does not conform. The list is only printable when its items are, so addWritabletoPoint. print(None).Noneisn’t printable in Mojo; the message saystype 'None'. To show “nothing”, print a word like"none", or use.or_else(...)on anOptional. AnOptional[Int]itself prints fine.- Generic code with a bound that doesn’t include
Writable(Fix 4).
Related errors
Section titled “Related errors”'X' does not implement the '__eq__' method: the same idea for==,<and+on your own types.'X' value has no attribute 'Y': your struct doesn’t have the field or method you asked for.- All Mojo error pages: the full list.
Practice
Section titled “Practice”1. Print a temperature
Section titled “1. Print a temperature”Make Reading printable so the program prints Oslo: -3.5 C.
@fieldwise_initstruct Reading: var city: String var celsius: Float64
def main(): var r = Reading("Oslo", -3.5) print(r)Hint: add the trait and a write_to method that writes the city, ": ", the number and " C".
Show solution
@fieldwise_initstruct Reading(Writable): var city: String var celsius: Float64
def write_to(self, mut writer: Some[Writer]): writer.write(self.city, ": ", self.celsius, " C")
def main(): var r = Reading("Oslo", -3.5) print(r)Output:
Oslo: -3.5 CWritable tells print the type can be printed, and write_to decides how. Without write_to, it would print Reading(city=Oslo, celsius=-3.5).
printonly accepts types with theWritabletrait.- For your own struct, add it:
struct Point(Writable):. Mojo writes a default format. - Write
write_to(self, mut writer: Some[Writer])for your own format;__str__does nothing in Mojo. - A list is printable only if its items are;
Noneisn’t printable at all. - In generics, put
Writablein the bound:[T: Writable].
Next up: ‘X’ does not implement the ‘eq’ method, the error for == and friends on your own types.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Traits in the Mojo manual: what traits are and how types conform to them.
- Mojo traits cheat sheet: what each standard trait, including
Writable, gives you. printin the standard library: the full signature, withsep,end,fileandflush.- Mojo Printing Your Types: our lesson on
Writableandwrite_to.