23 — Modules: split your program into files
One file works for a small program. As a project grows, splitting it into modules keeps each file focused. NME imports only the names you list, so every module has a clear interface and nothing else leaks between files.
Steps
Put shared functions in a module file. A module is an ordinary
.nmefile that defines values instead of running a whole program:
run it →# shapes.nme def rect(width, height): return width * height def circle(radius): return 3.14 * radius * radiusImport the names you need in the main program:
# area.nme from "shapes.nme" import rect, circle show rect(4, 5) show circle(2)Run the main program; NME finds
shapes.nmenext to it:nme run area20 12.56The ready-made pair lives in
examples/modules/—area.nmeandshapes.nme, with_koKorean twins.The import name list is the interface. Only
rectandcirclecross intoarea.nme; anything else in the module stays private. Imported names can be used in sentences like any other value:from "shapes.nme" import rect show rect(3, 7)
Rules to remember
- The module file sits next to the main program.
- The file name is a Python identifier:
shapes.nme, notmy-shapes.nme. - Imports can chain: a module may import another module.
nme checkandnme buildcheck imported modules too.
Try it yourself
Add a perimeter(width, height) function to shapes.nme, import it in
area.nme, and show the perimeter of a 4 by 5 rectangle.
What you learned
from "helper.nme" import name1, name2imports only the listed names.- The module is a normal
.nmefile in the same folder. - Imported names work in sentences and calls like local values.
- A clear interface means no hidden global state between files.