Nox
Download

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:

JSON
{
  "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#

Nox
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 alias
Nox
import 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 ones

Forms:

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:

  1. The standard library — the nox.* modules (Standard library).
  2. The current project — a/b.nox under the project root (the directory containing nox.json); import helpers is <root>/helpers.nox and import utils.mathy is <root>/utils/mathy.nox.
  3. A dependency — the alias of an entry in requires is a package name: import nyx.app loads module app of the package aliased nyx.

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 with from util import LIMIT — util.LIMIT is not valid.
  • extern def functions (raw native bindings, such as sqrt in nox.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.

Nox
counter: int = 0

def bump() -> int:
    counter += 1
    return counter

print(bump(), bump())
Output
1 2

A 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:

Nox
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()
Output
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* or nox.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.atomic or nox.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 + 1 or obj.hits = obj.hits + 1 are not atomic: use a channel or nox.atomic for exact counters.
  • This includes plain nox.http.serve on 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:

Nox
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())
Output
11

The 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:

Text
# 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.