Language reference
Modules and packages
Programs and modules#
A module is a .nox file. A program is an entry file plus every module it imports, directly or transitively. All modules of a
program are compiled together as one unit: there is no separate compilation, no linking of precompiled Nox objects and therefore no
ABI to keep stable between your own modules.
A project is a directory with a nox.json manifest:
{
"name": "demo",
"entry": "main.nox",
"requires": []
}noxc init demo creates one. name and entry are required; requires lists third-party packages (see Packages).
Single-file programs need no manifest and can import only the standard library.
The entry point#
There is no main function. The top-level statements of the entry file run in order and form the program. A top-level function named
main is rejected because the compiler synthesises its own entry symbol with that name. The top-level statements of imported modules run too, once, before the statements of the module that imports them (modules are merged in dependency order, imports first); keep imported modules to declarations unless you want
that side effect. Module-level variable initialisers always run before any other top-level statement.
import#
import nox.strings # qualified use: nox.strings.upper(s)
from nox.math import sqrt, pi # direct use: sqrt(2.0)
from nox.strings import upper as up # alias
import nox.time as t # module aliasimport util # <project>/util.nox
import app.models # <project>/app/models.nox
from app.models import User, greet
x: util.Box = util.Box(2) # qualified type names work in annotations
y: util.Pair[int] = util.Pair[int](2) # so do generic onesForms:
| Statement | Effect |
|---|---|
import a.b |
makes the module's functions and classes available as a.b.name(...) and a.b.Class |
import a.b as m |
the same, under the alias m |
from a.b import x, y |
makes x and y available unqualified |
from a.b import x as z |
the same, renamed to z |
There is no from … import *. Imports are static: they must be at the top level of a module, are resolved before anything runs, and an
unresolved module is a compile error. Importing the same module twice is harmless. Cyclic imports are rejected.
How names are resolved#
A dotted module path is looked up in this order:
- The standard library — the
nox.*modules (Standard library). - The current project —
a/b.noxunder the project root (the directory containingnox.json);import helpersis<root>/helpers.noxandimport utils.mathyis<root>/utils/mathy.nox. - A dependency — the
aliasof an entry inrequiresis a package name:import nyx.apploads moduleappof the package aliasednyx.
Qualified access has two quirks#
- A module's functions and classes can be used qualified (
util.double(4),util.Box), but its module-level variables are read withfrom util import LIMIT—util.LIMITis not valid. extern deffunctions (raw native bindings, such assqrtinnox.math) are never name-mangled, so they are used unqualified after the import — see the notes on each standard-library page.
Module-level state#
Variables declared at the top level of a module are module-level variables. Functions of the same module read and assign them without
any global keyword (Statements). Initialisers run before any other top-level statement, in source order.
counter: int = 0
def bump() -> int:
counter += 1
return counter
print(bump(), bump())1 2A module-level variable that a function reads is initialised before main runs. Whatever its initialiser needs comes with it: a variable
the initialiser mentions is initialised in the same step, together with the attribute assignments (cfg.port = 80) and method calls
(names.append("a")) on those variables that precede the last such declaration in the file. This is what makes the common
"configure, then boot" shape work:
class Config:
name: str
def __init__(self, name: str) -> None:
self.name = name
cfg: Config = Config("dev")
cfg.name = "prod"
label: str = cfg.name + "!"
def show() -> None:
print(label)
show()prod!Statements after the last such declaration, and compound statements such as if or for, run in main after all initialisers. An
initialiser may not read a module variable that a function reads but that is declared after it; the compiler rejects that with a
message naming both variables instead of reading uninitialised memory.
Module-level state and the multi-core runtime#
What happens to module variables when several workers run depends on the program (details in Concurrency):
- In a program that uses
serve_multicore*ornox.thread.pool_run, each worker keeps its own copy of module state; that is what makes the handlers independent. Share data between those workers with channels,nox.atomicornox.sharedmem. - In every other program, lists, dicts, class instances and the other heap values held in module variables are shared between tasks whichever worker runs them, and the program
uses the whole worker pool. Access is memory-safe, but compound updates such as
x = x + 1orobj.hits = obj.hits + 1are not atomic: use a channel ornox.atomicfor exact counters. - This includes plain
nox.http.serveon the default LLVM backend: connections can be handled by any worker, so shared values stay consistent but plain-number read-modify-write updates can lose increments.
Only the variables' own initialisers (and method calls on them up to the last declaration a function reads) run for every worker. The one exception is route
registration: r.get(...), r.post(...), r.use(...) and the other calls on a nox.router.Router variable that directly follow its declaration
(only def, class and imports may sit between them) also run for every worker, so the usual router = Router() / router.get(...) layout works. Any other statement
placed after the last module variable, such as app.run() or db.seed() on your own objects, runs once, on the main worker. Put setup that every worker needs inside a
function and call it from the initialiser:
class Counter:
def __init__(self: Counter) -> None:
self.n = 0
def build() -> Counter:
c: Counter = Counter()
c.n = 10
return c
counter: Counter = build()
def bump() -> int:
counter.n = counter.n + 1
return counter.n
print(bump())11The same applies to a database connection (open it in the initialiser; each worker then has its own) and to routers: see nox.router.
Packages#
A package is an ordinary project whose repository can be listed in another project's requires. Dependencies are fetched into a cache,
pinned to an exact commit in nox.lock, and compiled into your program with everything else. The registry, the lock file, noxc add,
noxc publish and the trust implications are in Packages and The noxpkg registry.
A package that declares extern def bindings runs native code with full authority — see Security.
Visibility#
By default all top-level names of a module are importable; Nox has no public/private keywords. By convention a leading underscore marks a name as
internal, and names beginning with __nox_ belong to the compiler's prelude. A leading-underscore name is not hidden from importers.
__all__: an explicit public API#
A module that wants the compiler to enforce its public API declares a top-level list of string literals:
# mylib/util.nox
__all__: list[str] = ["public_add", "Box"]
def public_add(a: int, b: int) -> int:
return _helper(a) + b # the module itself can use everything
def _helper(a: int) -> int: ...
def internal_only(a: int) -> int: ...
class Box: ...
class Hidden: ...From another module, util.internal_only(...), util.Hidden(...), an annotation util.Hidden, and from util import internal_only are then compile errors:
'internal_only' is not part of the public API of module 'util' (it is not listed in that module's __all__). The listed names work exactly as before.
- The list applies to top-level functions and classes (the names the compiler qualifies by module). It is opt-in: a module without
__all__keeps exporting everything, so existing code is unaffected. - Every listed name must be a function or class defined in that module; a typo is an error (
__all__ of module 'util' lists 'nope', which is not a function or class defined there), not a silently hidden name. __all__must be a plain list of string literals; it is read at compile time and is not a runtime variable.- This is compile-time API hygiene, not a security boundary: it does not change what is linked into the program.