The Mojo ManualXYZ Homework Edition

⇩ Download ▾

Chapter 5: Metaprogramming

Many languages have facilities for metaprogramming: writing code that generates or modifies code. Python has facilities for dynamic metaprogramming: features like decorators, metaclasses, and many more. These features make Python very flexible and productive, but since they're dynamic, they come with run-time overhead. Other languages have static or compile-time metaprogramming features, like C preprocessor macros and C++ templates. These can be limiting and hard to use.

Mojo's compile-time metaprogramming system uses the same language as run-time programs, so you don't have to learn a new language—just a few new features. The primary features you'll need to learn are:

  • Compile-time statements and expressions
  • Compile-time parameters
  • Generics and traits

Adapted from the Mojo Manual, part of the Modular Platform repository (github.com/modular/modular), Copyright (c) Modular Inc., licensed under the Apache License v2.0 with LLVM Exceptions. Changes were made: reformatted as an accessible XYZ web edition with build-verified example outputs. Mojo is a trademark of Modular Inc.; this edition is not affiliated with or endorsed by Modular. License: Apache-2.0 WITH LLVM-exception.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.