Mojo Reflection
Say you want a debug printer that works for any struct: it should list every field and its value, without you writing a write_to for each struct. To do that, your code has to ask a type questions about itself: “what’s your name?”, “how many fields do you have?”, “what are they called?”. That’s reflection. In Mojo it all happens while building, so the finished program contains plain code, as if you’d written it by hand.
You’ve already used it
Section titled “You’ve already used it”When a struct conforms to Writable or Equatable without writing the methods, Mojo fills them in by looking at the fields. That’s reflection, done for you:
@fieldwise_initstruct Sensor(Equatable, Writable): var id: Int var label: String var reading: Float64
def main(): var a = Sensor(1, "kitchen", 21.5) var b = Sensor(1, "hall", 19.0) print(a) print(a == b, a != b)Output:
Sensor(id=1, label=kitchen, reading=21.5)False TrueNo write_to, no __eq__. The compiler went through the fields, checked that each one can be printed and compared, and wrote the code. The rest of this page shows how to do the same thing in your own functions.
A type’s name: reflect[T]
Section titled “A type’s name: reflect[T]”reflect[T] is the door to everything. It’s always available (no import needed), and it gives you static methods to call. The simplest ones return the type’s name:
@fieldwise_initstruct Player: var name: String var level: Int
def main(): print(reflect[Player].base_name()) print(reflect[List[String]].name()) print(reflect[List[String]].base_name()) print(reflect[Int].name())Output:
PlayerList[String]ListSIMD[DType.int, 1]base_name()is the bare name, without parameters.name()is the full name, with parameters. For your own structs it also starts with the module (the file name without.mojo), so inhello.mojoit’shello.Player.
That last line surprises people: Int reports itself as SIMD[DType.int, 1]. Int and Float64 are names for one-element SIMD types, and reflection shows what’s underneath. You’ll meet SIMD in Mojo SIMD.
Listing the fields
Section titled “Listing the fields”Three more methods tell you about a struct’s fields: field_count(), field_names() and field_types(). Combine them with a comptime for loop:
@fieldwise_initstruct Player: var name: String var level: Int var health: Float64 var alive: Bool
def show_fields[T: AnyType](): comptime count = reflect[T].field_count() comptime names = reflect[T].field_names() comptime types = reflect[T].field_types() print(reflect[T].base_name(), "has", count, "fields:") comptime for i in range(count): comptime field_name = names[i] comptime type_name = reflect[types[i]].name() print(" ", field_name, ":", type_name)
def main(): show_fields[Player]()Output:
Player has 4 fields: name : String level : SIMD[DType.int, 1] health : SIMD[DType.float64, 1] alive : BoolEverything here is worked out while building. The comptime for runs four times inside the compiler, and the finished program is just five print calls with the answers filled in.
Reading the fields of a value
Section titled “Reading the fields of a value”Names and types are about the struct. To get at the values inside one instance, use field_ref[i](value). It gives you the i-th field of value. Here’s the debug printer from the start of the page:
struct Secret: var code: Int
def __init__(out self, code: Int): self.code = code
struct Player: var name: String var level: Int var key: Secret
def __init__(out self, name: String, level: Int, code: Int): self.name = name self.level = level self.key = Secret(code)
def dump[T: AnyType](value: T): comptime names = reflect[T].field_names() comptime types = reflect[T].field_types() print(reflect[T].base_name(), "{") comptime for i in range(reflect[T].field_count()): comptime name = names[i] comptime if conforms_to(types[i], Writable): print(" ", name, "=", reflect[T].field_ref[i](value)) else: print(" ", name, "= <can't print>") print("}")
def main(): dump(Player("Ada", 7, 1234))Output:
Player { name = Ada level = 7 key = <can't print>}dump works for any struct. For each field it checks, while building, whether the field’s type is Writable. If it is, it prints the value; if not (like Secret), it prints a placeholder. The comptime if is what makes this legal: inside its branch the compiler knows the field can be printed.
Comparing two values field by field
Section titled “Comparing two values field by field”The same tools let you find which fields differ between two values, which is handy in tests and logs:
@fieldwise_initstruct Config: var host: String var port: Int var verbose: Bool
def changed_fields[T: AnyType](a: T, b: T) -> List[String]: comptime names = reflect[T].field_names() comptime types = reflect[T].field_types() var changes = List[String]() comptime for i in range(reflect[T].field_count()): comptime if conforms_to(types[i], Equatable): if reflect[T].field_ref[i](a) != reflect[T].field_ref[i](b): comptime name = names[i] changes.append(name) return changes^
def main(): var old = Config("localhost", 8080, False) var new = Config("localhost", 9090, True) print(changed_fields(old, new))Output:
[port, verbose]The comptime for and comptime if are decided while building. The != comparison is a normal run-time if, because it depends on the values.
One field by name
Section titled “One field by name”If you know a field’s name, you can ask for it directly with field["name"]. Its .T is the field’s type:
@fieldwise_initstruct Config: var host: String var port: Int
def main(): comptime host_info = reflect[Config].field["host"] var default_host: host_info.T = "localhost" print(default_host) print(reflect[Config].field_count())Output:
localhost2host_info.T is String here. If someone later changes host to another type, default_host follows. This only works on a concrete type like Config; inside a generic function over T, loop over the fields by index instead.
type_of: the type of a value
Section titled “type_of: the type of a value”Sometimes you have a value and need its type, for example to pass it as a parameter. type_of(x) gives you that, while building:
def make_default[T: Defaultable]() -> T: return T()
def main(): var count = 42 var price = 9.99 var fresh_count = make_default[type_of(count)]() var fresh_price = make_default[type_of(price)]() print(count, fresh_count) print(price, fresh_price) print(reflect[type_of(price)].name())Output:
42 09.99 0.0SIMD[DType.float64, 1]type_of(count) is Int, so make_default[Int]() builds a fresh Int, which is 0. type_of only looks at the type; it never reads the run-time value.
Function names and call sites
Section titled “Function names and call sites”Two more tools live in std.reflection, and you have to import them:
get_function_name[f]()returns a function’s name as written.call_location()tells a function where it was called from: file, line and column. It needs the function to be marked@inline(.always).
from std.reflection import get_function_name, call_location
def save_game(): pass
@inline(.always)def log(msg: String): print("line", call_location().line(), ":", msg)
def main(): print(get_function_name[save_game]()) log("starting") log("done")Output:
save_gameline 12 : startingline 13 : donelog reports the line of each call in main, not its own line. That’s how you build helpers like “check this, and if it fails, say where”. call_location() also has .file_name() (the full path to the file) and .column(). Keep the decorator: without it, the manual warns, the result depends on what the compiler happens to do. When we tried it on Mojo 1.2, log then reported its own print line instead of the caller’s.
What reflection can’t do (yet)
Section titled “What reflection can’t do (yet)”- It works on structs. For other kinds of types, check
reflect[T].is_struct()first. - Names come from the compiler and may change between versions; don’t parse them or save them to files.
- Some types print odd internal names, like
IntasSIMD[DType.int, 1], or types from deep inside the standard library.
Practice
Section titled “Practice”1. Field summary
Section titled “1. Field summary”Write summary[T: AnyType]() that prints the struct’s base name and how many fields it has, like Point has 2 fields. Test it with a Point struct that has x and y.
Hint: reflect[T].base_name() and reflect[T].field_count().
Show solution
@fieldwise_initstruct Point: var x: Int var y: Int
def summary[T: AnyType](): print(reflect[T].base_name(), "has", reflect[T].field_count(), "fields")
def main(): summary[Point]()Output:
Point has 2 fieldsBoth answers are compile-time values, so the program just prints two constants.
2. Count the Int fields
Section titled “2. Count the Int fields”Write count_ints[T: AnyType]() -> Int that returns how many fields of T are of type Int. Test it with a struct that has two Int fields and one String field.
Hint: loop over reflect[T].field_types() with comptime for, and test types[i] == Int with comptime if.
Show solution
@fieldwise_initstruct Item: var id: Int var name: String var stock: Int
def count_ints[T: AnyType]() -> Int: var count = 0 comptime types = reflect[T].field_types() comptime for i in range(reflect[T].field_count()): comptime if types[i] == Int: count += 1 return count
def main(): print(count_ints[Item]())Output:
2The loop and the type checks are decided while building, so the built count_ints[Item] adds 1 exactly twice.
- Reflection lets code ask a type about itself, while building, with no run-time cost.
reflect[T]is always available:name(),base_name(),field_count(),field_names(),field_types().- Loop over fields with
comptime for, and pick out one name withcomptime name = names[i]before printing it. reflect[T].field_ref[i](value)reaches a field’s value; guard it withcomptime if conforms_to(...).type_of(x)gives the type of a value, for use as a parameter.get_function_nameandcall_locationcome fromstd.reflection;call_locationneeds@inline(.always).- Reflection is new: names and details may change in later versions.
Next up: materialization, how compile-time values (like a list built by the compiler) become values your program can use.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Reflection: the official guide, with field diffs, trait methods built on reflection, layouts and source locations.
std.reflectionpackage: the list of reflection modules and what each one provides.Reflectedreference: every method onreflect[T], includingfield_offsetandis_struct.- Compile-time evaluation: how the compiler runs the code behind
comptime forandcomptime if.