Mojo Error: expressions must not appear at file scope
error: expressions must not appear at file scope; move this into a function body means you wrote code that does something, like a print or a function call, outside of any function. Python runs a file from top to bottom, so code at the top level is normal there. Mojo doesn’t: a program starts in main(), and everything that runs has to be inside a function. For the other errors in this series, see Mojo Errors Explained.
The error message
Section titled “The error message”def greet(name: String): print("Hi,", name)
greet("Ada")script.mojo:4:1: error: expressions must not appear at file scope; move this into a function bodygreet("Ada")^mojo: error: failed to parse the provided Mojo source moduleFile scope is the top level of the file: anything that starts in the very first column, not inside a def or a struct. Line 4, greet("Ada"), is at file scope, and it’s an expression (a piece of code that runs and produces a value). Mojo doesn’t allow those up there.
What it means
Section titled “What it means”At the top of a Mojo file you can only declare things: functions (def), structs, traits, imports and comptime constants. You can’t run anything there. The code that runs lives in functions, and the program starts by calling main().
You’ll see three wordings of the same rule, depending on what’s at the top level:
| At file scope | Error message |
|---|---|
A call or expression: print("hi"), greet("Ada"), x = 5 |
expressions must not appear at file scope; move this into a function body |
A variable: var x = 5 |
global variables are not supported; move this into a function body or use 'comptime' to declare a constant |
A statement: if ...:, for ...:, while ...: |
'if' must be contained in a function (or 'for', 'while') |
The fixes are the same for all three.
Why Mojo does this
Section titled “Why Mojo does this”Mojo is compiled. When you build a program, the compiler turns the whole file into machine code first, then the program starts at main(). There’s no “run the file from the top” step, so loose code at the top level has no moment to run. Keeping everything in functions also means there are no global variables that any function might change behind your back. The functions page of the Mojo manual explains main() and how a program starts.
How to fix it
Section titled “How to fix it”Fix 1: Move the code into main()
Section titled “Fix 1: Move the code into main()”This is the fix almost every time. Wrap the top-level code in def main(): and indent it by four spaces:
def greet(name: String): print("Hi,", name)
def main(): greet("Ada")Output:
Hi, AdaYour helper functions stay at the top level, next to main. Only the code that runs moves inside. The order doesn’t matter: main can call functions written below it.
Fix 2: Fix the indentation
Section titled “Fix 2: Fix the indentation”Sometimes the code was meant to be inside main, but one line lost its indentation:
def main(): var name = "Ada"print("Hi,", name)indent.mojo:3:1: error: expressions must not appear at file scope; move this into a function bodyprint("Hi,", name)^mojo: error: failed to parse the provided Mojo source moduleThe print starts in column 1, so it isn’t part of main any more. Indent it like the line above:
def main(): var name = "Ada" print("Hi,", name)Output:
Hi, AdaMojo uses indentation for blocks, just like Python. See Mojo Syntax if this is new.
Fix 3: Use comptime for a constant
Section titled “Fix 3: Use comptime for a constant”If the top-level line was a setting that never changes, like a greeting or a limit, make it a comptime constant. That’s allowed at file scope:
comptime GREETING = "Hello"comptime MAX_USERS = 3
def main(): print(GREETING, "to", MAX_USERS, "users")Output:
Hello to 3 usersA comptime value is fixed when the program is built, so you can’t change it later. If you need a value that changes while the program runs, create it with var inside main and pass it to the functions that need it. The Mojo Constants lesson covers comptime in detail.
Fix 4: Drop if __name__ == "__main__":
Section titled “Fix 4: Drop if __name__ == "__main__":”Python scripts often end with this:
if __name__ == "__main__": main()In Mojo that gives 'if' must be contained in a function. Delete both lines. Mojo already calls main() for you when you run the file with mojo run.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- A Python script pasted into a
.mojofile. Put the top-level lines intodef main():, addvarto each new variable (see implicit declaration), and drop the__name__check. - Quick experiments. Writing
print(2 + 2)alone in a file doesn’t work. It needsdef main():around it, even for one line. - A line that slipped out of a function while you were editing. Look at the column number in the message:
:1means the line starts at the very left.
A related message you might see: if a file has functions but no main, mojo run stops with module does not define a `main` function. Add a def main():. The Mojo Get Started lesson shows the smallest program.
Related errors
Section titled “Related errors”- implicit declaration of ‘x’ is not allowed: a new variable without
var, the next thing to fix in pasted Python code. - use of unknown declaration ‘x’: often appears right after a global variable error.
- All Mojo error pages: the full list.
Practice
Section titled “Practice”1. Turn a script into a program
Section titled “1. Turn a script into a program”This file came from Python. Make it build and print the three lines.
TAX = 0.2
def with_tax(price: Float64) -> Float64: return price * (1 + TAX)
prices = [10.0, 20.0]for p in prices: print(with_tax(p))print("done")Hint: the constant can stay at the top if you make it comptime. The rest goes into main, and a list needs a type: var prices: List[Float64] = [...].
Show solution
comptime TAX = 0.2
def with_tax(price: Float64) -> Float64: return price * (1 + TAX)
def main(): var prices: List[Float64] = [10.0, 20.0] for p in prices: print(with_tax(p)) print("done")Output:
12.024.0doneTAX never changes, so comptime is a good fit at file scope. The function stays where it was. The code that runs moved into main, and prices got a var and a type.
- At file scope you can only declare things:
def,struct,trait, imports andcomptimeconstants. - Code that runs goes inside a function, and the program starts at
main(). - A top-level
varisglobal variables are not supported; a top-leveliforforis'if' must be contained in a function. - Use
comptimefor top-level constants, and pass changing values as arguments. - Drop
if __name__ == "__main__":. Mojo callsmain()for you.
Next up: cannot implicitly convert ‘X’ value to ‘Y’, the error for a value of the wrong type.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Functions in the Mojo manual: how
defworks and why programs start atmain(). - Mojo tips for Python devs: what changes when you move code from a Python script to Mojo.
- Compile-time evaluation: how
comptimevalues work. - Mojo Get Started: the smallest Mojo program and how to run it.