Skip to main content
Log in

Mojo trait

Representable

A trait that describes a type that has a String representation.

Any type that conforms to the Representable trait can be used with the repr function. Any conforming type must also implement the __repr__ method. Here is an example:

@value
struct Dog(Representable):
var name: String
var age: Int

fn __repr__(self) -> String:
return "Dog(name=" + repr(self.name) + ", age=" + repr(self.age) + ")"

var dog = Dog("Rex", 5)
print(repr(dog))
# Dog(name='Rex', age=5)
@value
struct Dog(Representable):
var name: String
var age: Int

fn __repr__(self) -> String:
return "Dog(name=" + repr(self.name) + ", age=" + repr(self.age) + ")"

var dog = Dog("Rex", 5)
print(repr(dog))
# Dog(name='Rex', age=5)

The method __repr__ should compute the "official" string representation of a type.

If at all possible, this should look like a valid Mojo expression that could be used to recreate a struct instance with the same value (given an appropriate environment). So a returned String of the form module_name.SomeStruct(arg1=value1, arg2=value2) is advised. If this is not possible, a string of the form <...some useful description...> should be returned.

The return value must be a String instance. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

Note that when computing the string representation of a collection (Dict, List, Set, etc...), the repr function is called on each element, not the str() function.

Implemented traits

AnyType, UnknownDestructibility

Methods

__repr__

__repr__(self: _Self) -> String

Get the string representation of the type instance, if possible, compatible with Mojo syntax.

Returns:

The string representation of the instance.