Skip to main content

Mojo identifiers, keywords, and conventions reference

Every Mojo source file is built from tokens. This page covers the tokens you choose (identifiers), the tokens the language reserves (keywords), and the context-sensitive tokens that control how values are passed and bound (conventions).

Identifiers

Every time you declare a variable, define a function, or create a struct, you give it a name. That name is an identifier. Identifiers are how you refer to things in your code: count in var count = 0, Point in struct Point, greet in def greet().

This section covers what makes a valid identifier.

Regular identifiers

A regular identifier starts with a letter or underscore, followed by any combination of letters, digits, and underscores:

identifier → [a-zA-Z_][a-zA-Z0-9_]*

Such as:

foo
_private
MyStruct
basic_value

Identifiers are case-sensitive. MyStruct and mystruct are different names.

Escaped identifiers

An escaped identifier is enclosed in backticks. Backticks allow any characters except vertical whitespace and backticks themselves:

`struct`        # Use a keyword as a name
`日本語の変数`    # Non-ASCII identifier
`my value`      # Spaces in a name

Escaped identifiers are useful when calling into external code that uses a Mojo keyword as a name, or when writing identifiers in natural language. Empty backtick identifiers are not allowed.

Keywords

Keywords are reserved words with fixed meaning. They cannot be used as ordinary identifiers (use an escaped identifier if you need to).

Control flow

These keywords control which code runs and in what order.

KeywordPurpose
ifConditional execution
elifAdditional condition in an if chain
elseDefault branch in conditionals or loops
forIteration loop
whileConditional loop
breakExits the innermost loop
continueSkips to the next loop iteration
passNo-op placeholder statement
returnReturns from a function
withContext manager statement

Error handling

These keywords structure error propagation and recovery.

KeywordPurpose
tryBegins an error-handling block
exceptError handler clause
finallyAlways-execute clause in a try block
raiseRaises an error
assertRaises an error if a condition is false

Declarations

These keywords introduce new named entities.

KeywordPurpose
defFunction declaration
structStruct type declaration
traitTrait declaration
varScoped variable binding
refScoped reference binding

Keyword operators

Five operators are spelled as words rather than symbols. Symbolic operators (+, -, *, ^, //, etc.) are punctuation, not keywords.

KeywordPurposeKeywordPurpose
andLogical ANDorLogical OR
notLogical NOTinMembership test
isIdentity test

Imports

These keywords control module imports.

KeywordPurpose
importImports a module
fromSelective import from a module
asAliasing in imports and except clauses

Compile-time

KeywordPurpose
comptimeForces compile-time evaluation

Literal keywords

These keywords are also literals. They produce a value directly.

KeywordValueKeywordValue
Trueboolean trueFalseboolean false
NoneAbsence of a value (NoneType)SelfThe enclosing type

Case sensitivity

All keywords are case-sensitive:

  • True is a keyword; true is not.
  • None is a keyword; none is not.
  • Self is a keyword; self is a conventional argument name, not a keyword.

Conventions

Conventions tell the compiler how values are passed and how bindings are created. They are not reserved, so existing Python code that uses these names won't break, but in Mojo signatures they have fixed meaning.

Argument conventions appear before argument names in function signatures. They control ownership and mutability:

ConventionRoleMeaning
mutArgumentMutable reference to an existing value
outArgumentUninitialized output, used in initializers
deinitArgumentDestructive transfer at end of a value's lifecycle
varArgument or variableIndependent mutable owned copy of the value
refArgument or variableReference that doesn't own the value

var and ref also appear in variable declarations, where var creates a scoped mutable variable and ref creates a scoped reference binding:

struct Counter:
    var value: Int

    def __init__(out self):       # out: self doesn't exist yet
        self.value = 0

    def increment(mut self):      # mut: modifies self in place
        self.value += 1

var count = 0          # var creates a scoped mutable variable
ref alias = some_list  # ref binds a reference, no copy

raises and where also have fixed meaning in signatures. raises declares that a function can raise errors. where introduces a constraint clause on parameters:

def validate(value: Int) raises:
    if value < 0:
        raise Error("must be non-negative")

Was this page helpful?