Mojo Documentation (docstrings)
Back in Mojo Comments you met docstrings: the triple-quoted text at the top of a function that says what it’s for. Now that you write real programs, it’s worth doing them properly. Good docstrings show up when you hover over a name in VS Code, the compiler checks that they match your code, and the mojo doc command turns them into documentation data you can publish. This page covers all three.
Where docstrings go
Section titled “Where docstrings go”A docstring is the first string inside the thing it describes. For a field or a comptime value, it goes on the line after the declaration:
"""Small helpers for working with rectangles."""
@fieldwise_initstruct Rect(Copyable, Writable): """A rectangle with a width and a height."""
var width: Float64 """The width, in meters.""" var height: Float64 """The height, in meters."""
def area(self) -> Float64: """Returns the area of the rectangle.
Returns: The width times the height. """ return self.width * self.height
def scale(r: Rect, factor: Float64) -> Rect: """Makes a bigger or smaller copy of a rectangle.
Args: r: The rectangle to scale. factor: How much to multiply both sides by.
Returns: A new rectangle. """ return Rect(r.width * factor, r.height * factor)
def main(): var room = Rect(4.0, 2.5) print(room.area(), scale(room, 2.0).area())Output:
10.0 40.0| What | Where the docstring goes |
|---|---|
| Module (the file) | First thing in the file, before any imports |
| Function or method | First line of the body, right after the signature |
| Struct or trait | First line inside it, before the fields |
Field or comptime value |
On the line after it, at the same indentation |
| Package | First thing in the package’s __init__.mojo |
The docstrings don’t change what the program does. They’re for the people (and tools) reading the code.
The summary line
Section titled “The summary line”The first sentence is the summary. It’s what shows up in lists and search results, so make it short and complete. The official docstring reference suggests:
- Functions and methods: start with a verb in the present tense. “Returns the area of the rectangle.”
- Structs and traits: a noun phrase. “A rectangle with a width and a height.”
- Fields and constants: a noun phrase too. “The width, in meters.”
Start with a capital letter and end with a full stop. If you want to say more, leave a blank line after the summary and write a longer paragraph.
Sections: Args, Returns, Raises, Parameters
Section titled “Sections: Args, Returns, Raises, Parameters”After the summary, labelled sections describe the pieces of a function. Each label ends with a colon, and each entry under it is indented, written as name: Description.
"""Helpers for splitting work into batches."""
def batch_count[size: Int](total: Int) raises -> Int: """Counts how many batches of `size` items are needed for `total` items.
The last batch may be smaller than the others.
Parameters: size: How many items fit in one batch.
Args: total: How many items there are.
Returns: The number of batches, rounded up.
Raises: An error if `total` is negative. """ if total < 0: raise Error("total can't be negative") return (total + size - 1) // size
def main() raises: print(batch_count[10](95)) print(batch_count[4](8))Output:
102| Section | Describes |
|---|---|
Parameters: |
Compile-time parameters (the ones in [...]) |
Args: |
Normal arguments (Mojo uses Args, not Arguments) |
Returns: |
What the function gives back |
Raises: |
When it raises an error |
You don’t repeat the types: the tools read them from the signature. Mojo also understands an Examples: section, usually placed last, with a small piece of code in a fenced ```mojo block that shows how to call the function.
The compiler checks your docstrings
Section titled “The compiler checks your docstrings”Mojo reads docstrings while it builds your program, and warns when they don’t match the code. Here the summary starts with a small letter and has no full stop, and the Args: section names an argument that doesn’t exist:
def half(x: Float64) -> Float64: """returns half of a number
Args: y: The number. """ return x / 2
def main(): print(half(5.0))Output:
2.5The program still runs, but the compiler prints four warnings first:
half.mojo:2:8: warning: doc string summary should begin with a capital letter or non-alpha character, but this begins with 'r' """returns half of a number ^half.mojo:2:8: warning: doc string summary should end with a period '.', exclamation mark '!', question mark '?', or backtick '`', but this ends with 'r' """returns half of a number ^half.mojo:5:9: warning: unknown argument 'y' in doc string y: The number. ^half.mojo:4:5: warning: argument 'x' is not documented Args: ^That last pair is the useful one. When you rename an argument and forget the docstring, Mojo tells you. It also warns about a Returns: section on a function that returns nothing (“unexpected ‘Returns’ in doc string for function with no results”), and a Raises: section on a function that isn’t raises.
Generating docs with mojo doc
Section titled “Generating docs with mojo doc”Point mojo doc at a file (or a folder) and it collects every docstring:
mojo doc geometry.mojo -o api.jsongeometry.mojo here is the rectangle module from the first section, without the main function. Be aware of what you get: the official docs call mojo doc “an early version” of the tool. It writes JSON, not web pages, and the format may change. This is part of the file it made for us, trimmed:
{ "decl": { "kind": "module", "name": "geometry", "summary": "Small helpers for working with rectangles.", "functions": [ { "name": "scale", "overloads": [ { "signature": "def scale(r: Rect, factor: Float64) -> Rect", "summary": "Makes a bigger or smaller copy of a rectangle.", "args": [ { "name": "r", "type": "Rect", "convention": "imm", "description": "The rectangle to scale." } ], "returns": { "type": "Rect", "doc": "A new rectangle." } } ] } ], "structs": [ ... ] }, "version": "1.2.0"}Everything is there: the summary, each argument with its type and its description, the return value, and the Mojo version that made the file. Notice "convention": "imm": a plain argument is an immutable reference, which is the default you learned in Mojo Argument Conventions.
Turning the JSON into something readable
Section titled “Turning the JSON into something readable”Because it’s plain JSON, a few lines of Python can turn it into a list, a Markdown page or anything else. This script prints an overview of api.json:
import json
with open("api.json") as f: module = json.load(f)["decl"]
print("#", module["name"], "-", module["summary"])for fn in module["functions"]: for overload in fn["overloads"]: print(overload["signature"]) print(" ", overload["summary"])for struct in module["structs"]: print("struct", struct["name"], "-", struct["summary"]) for field in struct["fields"]: print(" var", field["name"] + ":", field["type"], "-", field["summary"]) for fn in struct["functions"]: for overload in fn["overloads"]: print(" ", overload["signature"], "-", overload["summary"])Running python3 list_docs.py printed:
# geometry - Small helpers for working with rectangles.def scale(r: Rect, factor: Float64) -> Rect Makes a bigger or smaller copy of a rectangle.struct Rect - A rectangle with a width and a height. var width: Float64 - The width, in meters. var height: Float64 - The height, in meters. def area(self) -> Float64 - Returns the area of the rectangle.The __init__ that @fieldwise_init made for Rect isn’t in the list: the tool skips code the compiler generated. Functions with a leading underscore and @doc_hidden ones are skipped too.
Finding what’s missing
Section titled “Finding what’s missing”Add --diagnose-missing-doc-strings and mojo doc lists every public name without a docstring. For a file with one function and one struct and no docstrings at all, we got this (source lines trimmed):
nodoc.mojo:1:1: warning: public module 'nodoc' is missing a doc stringnodoc.mojo:1:5: warning: public symbol 'half' is missing a doc stringnodoc.mojo:5:8: warning: public symbol 'Box' is missing a doc stringnodoc.mojo:6:5: warning: public symbol 'size' is missing a doc stringnodoc.mojo:8:9: warning: public symbol '__init__' is missing a doc stringIn a CI job you’d add -Werror so missing docstrings fail the build, and send the JSON nowhere:
mojo doc --diagnose-missing-doc-strings -Werror -o /dev/null src/It then ends with error: could not generate documentation and a non-zero exit code.
Practice
Section titled “Practice”1. Clear the warnings
Section titled “1. Clear the warnings”This program runs, but the compiler prints three docstring warnings. Fix the docstring so it builds without any.
def average(a: Float64, b: Float64) -> Float64: """the average of two numbers
Args: a: The first number. """ return (a + b) / 2
def main(): print(average(3.0, 4.0))Hint: look at the summary’s first letter, its last character, and which arguments are listed.
Show solution
def average(a: Float64, b: Float64) -> Float64: """Returns the average of two numbers.
Args: a: The first number. b: The second number.
Returns: The value halfway between `a` and `b`. """ return (a + b) / 2
def main(): print(average(3.0, 4.0))Output:
3.5The summary now starts with a capital letter and ends with a full stop, and b is documented. The Returns: section isn’t required for the warnings, but it belongs there.
2. Document a struct
Section titled “2. Document a struct”Add docstrings to this struct: one for the struct, one for each field, and one for the method, with a Returns: section.
@fieldwise_initstruct Temperature(Copyable): var celsius: Float64
def fahrenheit(self) -> Float64: return self.celsius * 1.8 + 32Hint: the field docstring goes on the line after var celsius: Float64.
Show solution
@fieldwise_initstruct Temperature(Copyable): """A temperature reading."""
var celsius: Float64 """The temperature in degrees Celsius."""
def fahrenheit(self) -> Float64: """Converts the temperature to Fahrenheit.
Returns: The same temperature in degrees Fahrenheit. """ return self.celsius * 1.8 + 32
def main(): print(Temperature(20.0).fahrenheit())Output:
68.0Each docstring describes the thing just above it (the struct’s opening line, the field, the method’s signature). mojo doc would now show a summary for all three.
- A docstring is a triple-quoted string placed first in a function, struct or file, or right after a field.
- Start with a one-sentence summary: capital letter, full stop, a verb for functions.
- Use
Args:,Returns:,Raises:andParameters:sections; don’t repeat the types. - The compiler warns when a docstring doesn’t match the code, like a missing or unknown argument.
mojo doc file.mojo -o api.jsonwrites the docs as JSON (no HTML yet).--diagnose-missing-doc-stringslists undocumented public names; add-Werrorin CI.
Next up: next steps, where to go once you’ve finished this tutorial.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Docstring reference: every section, the placement rules and all the compiler checks.
mojo doc: the command’s options, including-oand--diagnose-missing-doc-strings.@doc_hidden: hiding a public name from the generated docs.- Mojo standard library docs: a large real example of what docstrings turn into.
- PEP 257: the Python docstring conventions Mojo’s style is based on.