IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: 1.1.0
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

Mojo traits cheat sheet

What each standard library trait does, when you need it, and where it bites.

Lifecycle

AnyTypethe root; every type conforms automaticallytraits/anytype.mojo

no requirements

Deinitablehas an implicit destructor, called at last usetraits/deinitable.mojo

SignatureRemark
__deinit__(deinit self, /)provided
comptime __del__is_trivial: Boolcompile-time flag

Automatically added to every eligible type (all fields are also Deinitable). When the type is trivial, Mojo skips the destructor.

Movabletransfer ownership; enables the ^ operatortraits/movable.mojo

SignatureRemark
__init__(out self, *, deinit move: Self)provided
comptime __move_ctor_is_trivial: Boolcompile-time flag

Required to store a type in List, Optional, or Variant, or to return it by move.

Copyableexplicit copytraits/copyable.mojo

Refines: Movable

SignatureRemark
__init__(out self, *, copy: Self)provided
copy(self) -> Selfprovided
comptime __copy_ctor_is_trivial: Boolcompile-time flag

The copy constructor is synthesized if all fields are Copyable.

ImplicitlyCopyable(MARKER) lets copies be inserted implicitlytraits/copyable.mojo

Refines: Copyable < Movable · no new requirements

Can mask logical errors and hide code reasoning. Prefer Movable or Copyable.

Defaultablecreate with no argumentsbuiltin/value.mojo

SignatureRemark
__init__(out self)

Reach for this when you need parameterized default-construction without arguments.

RegisterPassable(MARKER) stored in registers, not memory; no stable address or identitybuiltin/value.mojo

Refines: Movable · no requirements (marker)

No stable address: you can't take the address of self in imm-convention methods. Identifiable is meaningless for these types.

Moved trivially; all fields must also conform.

TrivialRegisterPassable(MARKER) register-passable, copyable by moving bits, no side effectsbuiltin/value.mojo

Refines: ImplicitlyCopyable < Copyable < Movable, Deinitable, RegisterPassable · no requirements (marker)

A type whose values are treated as basic bit patterns. No constructors or destructors needed. All fields must also conform.

Format

Writableformat itself as text; works with print(), String(), format stringsformat/__init__.mojo

SignatureRemark
write_to(self, mut writer: Some[Writer])provided
write_repr_to(self, mut writer: Some[Writer])provided

If all fields conform, you inherit both methods through reflection.

Writera destination for a custom output targetformat/__init__.mojo

String, FileHandle, FileDescriptor conform

SignatureRemark
write_string(mut self, string: StringSpan)
write[*Ts: Writable](mut self, *args: *Ts)provided

Use for loggers, network streams, string builders, etc.

Testing

Strategyproduces random inputs for property-based teststesting/prop/strategy/__init__.mojo

Refines: Deinitable, Movable

SignatureRemark
Value: Copyable & Deinitableassociated type
value(mut self, mut rng: Rng) raises -> Self.Value

Allows strategies to carry and advance state between draws. value() draws one sample from the random number generator.

Accelerator traits

DevicePassablemarks a type as passable to an acceleratorbuiltin/device_passable.mojo

SignatureRemark
comptime device_type: AnyTypethe on-device type
_to_device_type(self, mut enc, ...)DeviceContext hook

A host type implements this so it can be handed to a GPU or other accelerator. DeviceContext calls the conversion hook to turn host into device at kernel launch.

DeviceTypeEncoderencodes host values into device layoutbuiltin/device_passable.mojo

SignatureRemark
target() -> _TargetTypedevice target
encode_device_ptr(mut self, ...)required
encode[T](mut self, value, dst)provided (+ fields, tuple, array)

Encodes a value's fields into the accelerator's data layout.

Compare & hash

Equatableequality; enables == and !=builtin/comparable.mojo

SignatureRemark
__eq__(self, other: Self) -> Boolprovided
__ne__(self, other: Self) -> Boolprovided

Don't use with floating-point values (use isclose()). NaN != NaN.

Mojo provides a fieldwise default. Override for caches, internal metadata, and custom behavior.

Comparableordered comparison; < > ≤ ≥, and sort()builtin/comparable.mojo

Refines: Equatable

SignatureRemark
__lt__(self, rhs: Self) -> Bool
__gt__(self, rhs: Self) -> Boolprovided
__le__(self, rhs: Self) -> Boolprovided
__ge__(self, rhs: Self) -> Boolprovided

Implement __lt__() unless it's expensive. If so, override all four.

Hashableproduces a hash; needed for Dict keys and Set elementshashlib/hash.mojo

KeyElement = Hashable + Equatable + Movable

SignatureRemark
__hash__(self, mut hasher: Some[Hasher])provided

Hasherimplements a hash algorithm (the algorithm, not a hashable type)hashlib/hasher.mojo

SignatureRemark
__init__(out self)
_update_with_bytes(mut self, data: Span[Byte, _])
_update_with_simd(mut self, value: SIMD[_,_])
update(mut self, value: Some[Hashable])
finish(var self) -> UInt64

Hashers remain alive after finalization. All three update methods are required.

Identifiableidentity; same-object test, enables is / is notbuiltin/identifiable.mojo

SignatureRemark
__is__(self, rhs: Self) -> Bool
__isnot__(self, rhs: Self) -> Boolprovided

Excludes register-passable types, which don't have stable addresses.

Convert

Boolable, Intable, Floatableconvert with Bool(), Int(), Float64()builtin/bool.mojo · builtin/int.mojo · builtin/floatable.mojo

SignatureRemark
__bool__(self) -> BoolBoolable
__int__(self) -> IntIntable
__int__(self) raises -> IntIntableRaising
__float__(self) -> Float64Floatable
__float__(self) raises -> Float64FloatableRaising

If the method raises, use the Raising variant.

Boolable unlocks if / while / and / or usage.

Math

Absable, Powable, Roundableunary math operatorsmath/math.mojo

SignatureRemark
__abs__(self) -> SelfAbsable · abs()
__pow__(self, exp: Self) -> SelfPowable · pow(), **
__round__(self) -> SelfRoundable · round()
__round__(self, ndigits: Int) -> SelfRoundable · round(), precision

Ceilable, Floorable, Truncableround toward a boundmath/math.mojo

SignatureRemark
__ceil__(self) -> SelfCeilable · ceil()
__floor__(self) -> SelfFloorable · floor()
__trunc__(self) -> SelfTruncable · trunc()

CeilDivable, CeilDivableRaisingceiling division (rounds up instead of down)math/math.mojo

SignatureRemark
__ceildiv__(self, denominator: Self) -> SelfCeilDivable
__ceildiv__(self, denominator: Self) raises -> SelfCeilDivableRaising

DivModablecombined division and modulo; enables divmod()math/math.mojo

Refines: ImplicitlyCopyable < Copyable < Movable

SignatureRemark
__divmod__(self, denominator: Self) -> Tuple[Self, Self]

Math outlier. The tuple is (quotient, remainder).

Iterate

Sized, SizedRaisinghas a length; enables len()builtin/len.mojo

SignatureRemark
__len__(self) -> IntSized
__len__(self) raises -> IntSizedRaising

Iterableiterate by borrowingiter/__init__.mojo

SignatureRemark
IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]]: Iteratorassociated type
__iter__(ref self) -> Self.IteratorType[origin_of(self)]

Parameterized on mutability and origin. Yields references tied to the source lifetime.

IterableOwnediterate by consuming and owningiter/__init__.mojo

SignatureRemark
IteratorOwnedType: Iteratorassociated type
__iter__(var self) -> Self.IteratorOwnedType

No origin tracking.

Iteratorproduces elements one at a time; the for-loop workhorseiter/__init__.mojo

Refines: Deinitable, Movable

SignatureRemark
Element: Movableassociated type
__next__(mut self) raises StopIteration -> Self.Element
bounds(self) -> Tuple[Int, Optional[Int]]provided
nth(var self, n: Int) -> Optional[Self.Element]provided

Requires an Iterable on the collection, and Iterator on the iterator. Don't rely on bounds() for safety checks. It's a hint.

Typed raises (StopIteration).

Interop

PathLikerepresents a file system pathos/pathlike.mojo

Path conforms

SignatureRemark
__fspath__(self) -> String

ConvertibleToPythoncan be sent to Pythonpython/conversions.mojo

Refines: Deinitable

SignatureRemark
to_python_object(var self) raises -> PythonObject

ConvertibleFromPythoncan be created from a Python objectpython/conversions.mojo

Refines: Copyable < Movable, Deinitable

SignatureRemark
__init__(out self, *, py: PythonObject) raises