Amoebatu

Dolphin Language Reference

What the interpreter actually does today. Last updated 2026-11-26: paths and directories, compression, archives, count_lines(), array() and parallel fills.

doc/LANGUAGE.md is the design draft: why things are the way they are, and what is planned. This file is the other half: the language as implemented, checked against the source (src/dolphin/src/) and by running programs. When the two disagree, this file describes current behaviour and LANGUAGE.md describes intent.

Dolphin looks like Python and most small Python programs run unchanged. The differences are listed first, because they're what trips you up.


1. Coming from Python: the differences #

Not in the language (yet) #

PythonDolphinWhat to write instead
x is None, is notno is operator (syntax error)x == None, x != None
a if c else bno conditional expressionan if/else statement
a, b = 1, 2, return a, b, (1, 2)no tuples, no unpackingreturn a list: return [a, b], then r[0], r[1]
for k, v in d.items()no items(), no unpackingfor k in d: then d[k]
global X / nonlocalno such statementssee §6.2 (mutate a global list/dict, or return values)
lambda, closuresreserved / rejecteda module-level def, passing what it needs as arguments
classno classes, structs or objects yetdicts for records; struct is reserved for later
importreserved, not implementedone file per program for now
os.listdir, os.makedirs, os.stat, glob.globno os modulePath (§9.7), which works like pathlib
gzip.open, zipfile, tarfileno modulesdecompress(read_file(p)) (§9.8), Archive (§9.9)
try … finally / elsenot supportedexcept clauses only
except (A, B):no tuple of classestwo except clauses, or catch a common parent
user-defined exceptionsnot possible (no classes)raise a builtin one with a message (DecodeError("..."))
s[::2], any slice stepnot supporteda loop or comprehension
x[1:3] = ...no slice assignmentbuild a new list
del x[k]no deld.pop(k) / lst.pop(i)
sets, {x for ...}, dict comprehensions, generator expressionsnot supportedlists, dicts built in a loop
a = b = 0no chained assignmenttwo statements
a = 1; b = 2no ;one statement per line
while … else, for … elseno loop elsea flag variable
*args, **kwargs, f(*lst)not supportedpass a list or dict
"%d" % n, "{}".format(n)neitherf-strings
f"{x!r}", f"{x=}"no conversions or =f"{repr(x)}"
print(a, end=""), sorted(xs, key=...)builtins and methods take no keyword argumentsbuild the whole line, then print it
"é", "\N{...}"no \u/\N escapes (SyntaxError)put the character in the source (UTF-8), or chr(0xE9)
obj.attr = vno attribute assignmentdict item assignment

Missing builtins people reach for: enumerate, zip, map, filter, any, all, round, list(), dict(), isinstance, hex, input, open. Use range(len(xs)) for enumerate, int(x + 0.5) or an f-string spec for rounding, lst[0:] to copy a list, type(x) == "int" for type tests, and Stream / read_file / Path for files. Missing methods: str.rjust/ljust/zfill/ partition/index/title, list.insert/remove/sort/reverse, dict.items/update. Use f-string alignment for padding (f"{s:>8}") and sorted(xs) for sorting.

Things that behave differently #


2. Running programs #

dolphin prog.dol [args...]      # run; calls main(*args) if main is defined
dolphin --check prog.dol        # parse + resolve + analyze only (finds every NameError)
dolphin --needs prog.dol        # what each function needs, and whether it can run in parallel
dolphin --threads 1 prog.dol    # sequential reference execution
dolphin --engine pcode prog.dol # p-code engine (same semantics, faster)
dolphin -c prog.dol             # compile to prog.dcl; `dolphin prog.dcl` runs it
dolphin --ast / --tokens / --disasm / --stats / --trace prog.dol

Program structure #

  1. The whole file is parsed, every name is resolved, and the needs analysis runs. Any syntax error or undefined name stops here, before anything runs.
  2. Module-level statements run top to bottom (they can print, assign globals, loop, catch exceptions, and so on).
  3. If the module defined a function main, it is called with the command-line arguments, each as a str. Too few arguments for main's parameters (without defaults) is a TypeError. Extra ones are also a TypeError.
  4. If main returns an int, that is the process exit code; otherwise 0.
  5. An uncaught exception prints file.dol:LINE: Kind: message on stderr (after all earlier output has been flushed) and exits with 1.
def main(path, limit="10"):      # dolphin prog.dol data.txt  /  dolphin prog.dol data.txt 50
    n = int(limit)
    ...
    return 0

3. Lexical structure #

Lines and indentation #

Identifiers and keywords #

Identifiers: ASCII letter or _, then letters, digits, _. Case-sensitive.

Keywords:

def return if elif else while for in break continue pass try except as
raise and or not True False None

Reserved, can't be used as names, not implemented yet:

lambda import from struct layout extern needs mut

Note that needs and mut are reserved, so they can't be variable names.

Numbers #

FormExampleType
decimal42, 1_000_000int
hex / binary / octal0xFF, 0b1010, 0o755int
float3.14, .5, 1., 1e-3, 6.02E23float

Underscores are digit separators anywhere in the digits. There are no negative literals: -5 is unary minus applied to 5. An integer literal above 9223372036854775807 is a syntax error.

Strings and bytes #

'single'   "double"   '''triple
can span lines'''   """also triple"""
r"raw \n stays two characters"
b"bytes"   rb"raw bytes"   br"same"
f"formatted {x}"   rf"raw formatted {x}"
"adjacent " "literals " f"concatenate {n}"

4. Values and types #

Typetype(x)Mutable?Notes
None"None"the single value None
bool"bool"True, False; acts as 1/0 in arithmetic
int"int"signed 64-bit; overflow raises OverflowError
float"float"IEEE double; prints like Python (0.1, 2.0, 1e+20)
str"str"noUTF-8 text; length and indices count code points
bytes"bytes"noraw bytes; indexing gives an int 0..255
list"list"yesshared by reference
dict"dict"yesshared by reference; keeps insertion order
function"function"a def; can be passed around and called
builtin"builtin"e.g. len
exception class"exception class"e.g. ValueError
exceptionits class namewhat except E as e binds
Path"Path"noa filesystem path, §9.7
Stream, Response, JSON, Listener, ArchivesameI/O objects, §9

References and copying #

Assignment never copies. b = a makes both names refer to the same list or dict, so b.append(1) is visible through a. Strings, bytes and numbers can't change, so sharing them is invisible.

Truthiness #

False: None, False, 0, 0.0, "", b"", [], {}. Everything else is true, including every Stream, function and exception.

Equality #

Ordering (<, <=, >, >=) #

Allowed between numbers (int/float/bool mixed), between two str (code point order), and between two bytes. Anything else, including None or lists, raises TypeError. Comparisons involving NaN are false.

Dict keys #

Keys can be None, bool, int, float, str, bytes, functions and exception classes. A list or dict as a key is TypeError: unhashable type. Numbers that are equal are the same key: d[1], d[1.0] and d[True] are one entry. Iteration order is insertion order; reassigning an existing key keeps its position.


5. Expressions #

Operator precedence (lowest to highest) #

LevelOperatorsNotes
1orshort-circuit; returns an operand, not a bool
2andshort-circuit; returns an operand
3notprefix
4== != < <= > >= in not inchain: a < b < c means a < b and b < c
5|
6^
7&
8<< >>
9+ -
10* / // %
11unary - + ~-2 ** 2 == -4
12**right-associative: 2 ** 3 ** 2 == 512
13call f(x), index a[i], slice a[i:j], attribute a.bleft to right

Parentheses group. (a, b) is an error ("tuples are not supported yet").

Arithmetic #

ExpressionResult
int + - * intint, OverflowError on overflow
anything with a floatfloat
a / balways float (7 / 2 == 3.5, 4 / 2 == 2.0)
a // bfloor division: 7 // 2 == 3, -7 // 2 == -4 (float if either is float)
a % bresult takes the divisor's sign: -7 % 2 == 1
int ** intint if the exponent is ≥ 0, float if negative (2 ** -1 == 0.5)
x / 0, x // 0, x % 0ZeroDivisionError, for floats too
& | ^ ~ << >>ints only. << raises OverflowError if bits are lost; negative shift counts raise ValueError
str + str, bytes + bytes, list + listconcatenation (new object)
str * int, bytes * int, list * int (either order)repetition; a negative count gives empty
True + 12 (bools are ints in arithmetic)

Mixing str and numbers ("a" + 1) is a TypeError. Convert with str().

Membership: in / not in #

Right sideLeft sideMeaning
strstrsubstring test ("KT" in g)
bytesbytes or intsub-bytes, or a byte value
listanythingsome element == it
dicta valid keykey is present

Indexing and slicing #

s[0]   s[-1]          # str: a 1-character str; bytes: an int; list: the element
d["key"]              # dict: KeyError if missing (use d.get("key") for None)
s[2:5]  s[:3]  s[3:]  s[-2:]  s[:]   # new str / bytes / list

Calls #

f(1, 2)          f(1, b=2)          f(a=1, b=2)

List comprehensions #

[expr for name in iterable]
[expr for name in iterable if condition]

One for and at most one if. No nesting of fors inside one comprehension (nest whole comprehensions instead). When expr is a call to a pure function, the comprehension becomes a parallel map (§10).

f-strings #

f"{station:<5} {temp:6.1f} {count:,} {flag}"

Each {...} holds an expression, optionally followed by :spec. {{ and }} are literal braces. Without a spec, the value is shown as str() would show it. The spec is the format mini-language below.

Format spec #

[[fill]align][sign][0][width][,][.precision][type]

PartValues
align< left, > right, ^ center. Default: numbers right, text left
fillany one character before the align: f"{x:*^9}"
sign+ always, - negatives only (default), space: space for positives
0zero-pad numbers after the sign: f"{7:03d}" == "007"
widthminimum width in code points
,thousands separators: f"{1234567:,}" == "1,234,567"
.precisiondigits after the point (f, e, %), significant digits (g), max characters (s)
typed x X o b for ints; f F e E g G % for numbers; s for strings

A float with a precision but no type uses g. Using d on a float, or f on a string, raises ValueError.

f"{3.14159:.2f}"   # 3.14
f"{3.14159:8.3f}"  # '   3.142'
f"{42:05d}"        # 00042
f"{255:x}"         # ff
f"{0.5:%}"         # 50.000000%
f"{-3:+d}"         # -3
f"{'s':<4}|"       # 's   |'

6. Statements #

6.1 The statement list #

x = expr                      # assignment: target is a name, a[i], or d[k]
x: int = expr                 # annotation (parsed, not enforced); needs a value
x += expr                     # also -= *= /= //= %= **= &= |= ^= <<= >>=
name << expr                  # assigns, see §1 and §9.4
expr                          # expression statement (usually a call)
pass
break
continue
return [expr]                 # no value: returns None
raise [expr]                  # §8

if cond:  ...
elif cond: ...
else: ...

while cond: ...

for name in iterable: ...     # exactly one name

def name(params) -> ret: ...  # §7

try: ...
except ClassName as e: ...
except ClassName: ...
except: ...                   # catches everything

for iterates over:

IterableYields
listits elements (a snapshot taken when the loop starts)
dictits keys in insertion order (also a snapshot)
str1-character strings (code points)
bytesints 0..255

Changing a list or dict while looping over it doesn't affect the loop. The loop variable keeps its last value after the loop.

6.2 Scope #

There are exactly two levels: the module (globals) and the function (locals).


7. Functions #

def decode(line: str, strict=False, width: int = 80) -> dict:
    ...
    return result

8. Exceptions #

Hierarchy #

Error
├── ValueError
│   └── JSONError
├── TypeError
├── IndexError
├── KeyError
├── NameError
│   └── UnboundLocalError
├── AttributeError
├── ZeroDivisionError
├── OverflowError
├── IOError
├── DecodeError
├── RecursionError
├── RuntimeError
└── SyntaxError

except Error catches everything that can be raised. DecodeError is meant for your own parsers ("this input is malformed"); bytes.decode() also raises it for invalid UTF-8.

Raising #

raise ValueError("bad wind group: " + g)   # class called with one argument (converted with str)
raise DecodeError                          # no message
raise                                      # inside an except block: re-raise the current one

Only builtin exception classes exist; you can't define new ones. Exception constructors take at most one argument.

Catching #

try:
    v = int(field)
except ValueError as e:
    print(e.kind, e.message)    # "ValueError", "invalid literal for int(): 'x'"
    v = None

Errors the runtime raises #

SituationException
int("abc"), float("x")ValueError
wrong argument types, "a" + 1, calling a non-functionTypeError
list/str/bytes index out of range, be_u32 past the endIndexError
missing dict key with d[k]KeyError (message is the key's repr)
x.nosuchmethodAttributeError
int overflowOverflowError
file or socket failureIOError
invalid UTF-8 in bytes.decode()DecodeError

9. Builtins and methods #

9.1 Builtin functions #

FunctionMeaning
print(a, b, ...)str() of each, space-separated, plus a newline. print() prints an empty line. No end=/sep=.
len(x)str (code points), bytes, list, dict
range(stop), range(start, stop[, step])a list of ints; step 0 raises ValueError
str(x)text form (str() with no argument is ""). str(b"x") is "b'x'"; use .decode() for text
repr(x)quoted form: repr("a") == "'a'"
int(x)from int, bool, float (truncates toward zero), or str
int(s, base)str in a base; int("ff", 16) == 255, int("0x1f", 16) == 31
float(x)from a number or str ("nan", "inf" accepted)
bool(x)truthiness
abs(x)int or float
min(a, b, ...), min(list); max likewisenumbers or strings, not mixed; empty list raises ValueError
sum(list)numbers; int unless a float is involved
sorted(list), sorted(dict)new ascending list (dict: its keys); all numbers or all strings; stable. No key/reverse
ord(c), chr(n)code point of a 1-character str, and back
type(x)type name as a str
read_file(path)the whole file as bytes (IOError if it can't be read)
array(n[, fill])a list of n copies of fill (default None), allocated once. Same as [fill] * n. A list or dict fill is shared by every slot, as in Python. See §10 for filling it in parallel
compress(data, format[, level]), decompress(data[, format]), compressors()§9.8
Path(...), Stream(target), JSON([x]), Listener(...), Archive(path[, mode])objects, below

int(s) and float(s) accept surrounding whitespace but nothing else extra: int(" 42 ") works, int("42KT") raises ValueError. int("012") is 12.

9.2 Binary decoding (big-endian, bounds-checked) #

All take (buf: bytes, offset: int) and raise IndexError with the offset and buffer size if the read runs past the end.

FunctionReads
be_u8, be_u16, be_u32, be_u64unsigned ints (be_u64 raises OverflowError above 2^63−1)
be_i16sm, be_i32smsign-magnitude ints (GRIB style: top bit is the sign)
be_f32, be_f64IEEE floats
bits(buf, bit_offset, nbits)unsigned big-endian bit field, nbits 0..63

examples/grib_ls.dol uses all of these.

9.3 Methods #

str (returns new strings; the original never changes)

MethodNotes
upper(), lower()ASCII only
strip([chars]), lstrip([chars]), rstrip([chars])default: whitespace. chars is a set of (ASCII) characters
split()on runs of whitespace, no empty pieces
split(sep)on exact sep; keeps empty pieces ("a,,b".split(",") == ["a", "", "b"]). No maxsplit
sep.join(list_of_str)
startswith(s), endswith(s)one string, not a tuple
find(s)code point index or -1. No start argument
count(s)non-overlapping occurrences
replace(old, new)all occurrences; empty old raises
isdigit(), isalpha(), isspace()ASCII; false for ""
encode()UTF-8 bytes

bytes: decode() (UTF-8, DecodeError if invalid), find(sub[, start]) (byte offset or -1), startswith(b), endswith(b), hex().

list: append(x), extend(iterable), pop([i]) (default last), index(x) (ValueError if absent), count(x).

dict: get(k[, default]) (default None), pop(k[, default]) (removes; KeyError without a default), keys(), values() (both lists).

Path, Stream, Archive: see §9.5, §9.7 and §9.9.

Exception values have the fields kind and message.

9.4 JSON #

JSON is an immutable document. JSON() is null; JSON(x) loads x.

j = JSON()
j << text                 # parse a str; JSONError (a ValueError) with line/column if malformed
j << {"stn": "KBCB", "t": 14.5}   # or load a dict / list / scalar
d << j                    # d = j.value(): dict, list or scalar (d needn't exist yet)
j.toString()              # compact text
j.prettyPrint()           # indented two spaces

Keys must be strings and come out sorted. Bytes become data:<mime>;base64,... strings and turn back into bytes when read. NaN or infinity raises ValueError. Details: src/dolphin/README.md, section JSON.

9.5 Stream: files and network #

Stream(target) is the one I/O object. The target decides what it is:

TargetKindNeeds
"path", "file://path" or a Pathfile, opened read-only immediatelyIO
"http://...", "https://..."HTTP: GET on the first read, POST on writeNetwork
"tcp://host:port", "unix:///path"connected socketNetwork
f = Stream("obs.txt")
if not f.valid:                 # opening never raises: check valid / error
    print("cannot open:", f.error)
    return 1
line = f.readline()             # bytes including the "\n"; b"" at end of file
chunk = f.read(4096)            # up to n bytes; b"" at end of file
rest = f.read()                 # everything that's left
f.close()

out = Stream("result.txt")      # invalid until opened for writing:
out.open("wc")                  # r, rw, wc (create/truncate), a (append). Returns the new valid
out.write("text\n")             # str or bytes; returns the byte count
out.seek(0, 0); out.tell()      # files only (IOError on pipes and sockets)

n = Stream("obs.txt").count_lines()   # how many lines readline() would return

count_lines() counts every "\n", plus a last line that doesn't end with one (so "a\nb" is 2 lines and "" is 0). A file is counted from its start however much of it has been read, and the read position is left where it was. It reads in 64 KB blocks without building any strings, so a million-line file takes milliseconds. On an HTTP stream it counts the rest of the body; on a socket it raises IOError (a socket has no end to count to).

9.6 Listener: servers #

Listener(port) / Listener("tcp://host:port") / Listener("unix:///path"), configure (bind, threads, per_connection, limit, set_timeout, drain), then start(handler) and wait(). Each connection calls handler(conn) with a connected Stream on a worker thread. A handler that might modify a global list or dict is refused at start() (ValueError). Full description in src/dolphin/README.md; example in examples/echo_server.dol.

9.7 Path: files and directories #

Path works like Python's pathlib.Path. A Path is an immutable value, and building or taking one apart never touches the disk. The methods that do touch the disk need IO.

d = Path("data") / "2026" / "11"       # join with /; Path("data", "2026", "11") is the same
d.mkdir()                              # creates missing parents too; fine if it exists
for p in d.iterdir():                  # sorted
    if p.suffix == ".txt" and p.is_file():
        print(p.name, p.stat()["size"])
for p in Path("data").rglob("*.grib2"):   # recursive, sorted
    ...
f = Stream(d / "obs.txt")              # Stream, Archive and read/write methods accept a Path

Text is kept normalized, with forward slashes: Path("a//b/./c/") is a/b/c, and Path() is .. .. is kept as written (only resolve() can remove it, because that needs the filesystem). str(p) gives the text and repr(p) gives Path('a/b/c'). Paths compare and sort by their text, can be dict keys, and sorted() takes a list of them.

Pure (no filesystem access):

Path("data/obs.tar.gz") gives
p.name"obs.tar.gz"
p.stem"obs.tar"
p.suffix".gz" ("" for .bashrc or README)
p.parentPath('data') (Path("a").parent is ., Path("/").parent is /)
p.parts["data", "obs.tar.gz"] (an absolute path starts with "/")
p / "x", "dir" / p, p / qjoined; an absolute right side replaces the left, as in pathlib
p.joinpath(a, b, ...)same as p / a / b
p.with_suffix(".zip")Path('data/obs.tar.zip'); "" removes the suffix
p.with_name("x.csv")Path('data/x.csv')
p.is_absolute()False

Filesystem (IO):

MethodReturnsNotes
exists(), is_dir(), is_file()boolnever raise
iterdir()list of Pathentries of a directory, sorted
glob(pattern)list of Path, sorted*, ?, [abc], [a-z], [!x] within a name; ** for any number of directories ("**/*.csv"); / between levels ("*/obs/*.txt"). * also matches names starting with .
rglob(pattern)list of Path, sortedglob("**/" + pattern): everywhere below
mkdir([mode])bool: whether it was createdcreates parents; an existing directory is fine (False); an existing file raises. mode (e.g. 0o750) applies to the new directory
rmdir()Noneempty directories only
unlink()Nonefiles and symlinks; a directory raises (use rmdir())
rename(target)the new Pathtarget is str or Path
touch()Nonecreates an empty file, or updates the modification time
stat()dictsee below
chmod(mode)Nonep.chmod(0o640)
resolve()Pathabsolute, with symlinks and .. resolved
read_bytes(), read_text()bytes / strread_text() raises DecodeError if the file isn't UTF-8
write_bytes(b), write_text(s)int: bytes / characters writtencreate or replace the file

stat() returns a dict with size, mode (permission bits as an int: f"{st['mode']:o}" prints 640), perms (ls-style text: "-rw-r-----", "drwxr-xr-x"), mtime, atime, ctime (float seconds since the epoch), uid, gid (0 on Windows), is_dir, is_file, is_link.

Every failure raises IOError, with the path and the reason in the message ("data/x: No such file or directory").

Differences from pathlib to know about:

9.8 Compression #

raw = decompress(read_file("obs.csv.gz"))         # format detected from the data
z = compress(text, "zstd")                        # str is compressed as its UTF-8 bytes
z = compress(data, "xz", 9)                       # optional level
print(compressors())                              # what this build supports
FormatFilesLevel (default)
"gzip".gz0..9 (6)
"zlib"zlib streams (Python's zlib.compress)0..9 (6)
"deflate"raw deflate, no header0..9 (6)
"bz2".bz21..9 (9)
"xz".xz0..9 (6)
"zstd".zst1..22 (3)

9.9 Archive: zip, tar, 7z #

Archive reads and writes archive files. The method names are Python's zipfile ones. It needs libarchive at compile time (dolphin --features lists archive); without it every Archive is invalid and says why.

a = Archive("obs.tar.gz")                # read: any format libarchive knows
if not a.valid:
    print(a.error)
a.namelist()                             # ["2026/", "2026/obs.txt", ...] in archive order
a.infolist()                             # [{"name", "size", "mode", "mtime", "is_dir"}, ...]
data = a.read("2026/obs.txt")            # bytes; KeyError if there's no such member
a.extractall("out")                      # extract everything; returns the names written
a.extractall("out", ["2026/obs.txt"])    # or only these members

w = Archive("bundle.zip", "w")           # write: the format comes from the name
w.writestr("notes.txt", "some text")     # a member from str or bytes
w.write("data/obs.txt")                  # a file from disk, stored under the same name
w.write(Path("data"), "obs")             # a directory, recursively, stored under "obs/"
w.close()                                # finishes the file: call it

10. Needs, purity and parallelism #

You never write threads. The analyzer works out what each function needs, and the runtime runs independent pure calls in parallel when that's worth it. The output is always identical to sequential execution. To get parallelism, you only need to know what makes a function pure.

What a function needs #

dolphin --needs prog.dol prints one line per function:

NeedComes from
purenothing below
IOprint, read_file, file streams, Path methods that touch the disk, Archive
Networkhttp/tcp/unix streams, Listener

Needs are transitive: a function that calls a function that prints needs IO too. Calls the analyzer can't resolve (through a variable) count as needing everything.

What can run in parallel #

A function can run on another thread when it is pure and it never modifies an object it didn't create itself (a parameter, a global, or anything reachable from one). Building a new list or dict and filling it is fine.

def decode(line):          # pure, builds its own dict: parallel
    r = {}
    r["stn"] = line[0:4]
    return r

def decode_into(line, r):  # modifies its parameter: always inline
    r["stn"] = line[0:4]

def decode_and_show(line): # prints: IO, inline, and so is everything that calls it
    print(line)

Where parallelism happens #

Filling a preallocated array in parallel #

When a decoder knows early how many records there are, it can allocate the result once and fill it by index:

def decode_all(buf, offsets):
    out = array(len(offsets))              # or [None] * len(offsets)
    for i in range(len(offsets)):
        out[i] = decode_record(buf, offsets[i])
    return out

If decode_record is parallel-safe, that loop runs as a parallel map: the calls run in batches on the thread pool, then the results are stored into out in loop order. The output is exactly what the sequential loop produces, including on failure. If record 37 raises, slots 0..36 are filled, 37 onward are untouched, i is 37, and the error is record 37's. On a 16-core machine a 4,000-record fill with ~0.7 ms per record ran 6× faster on 8 threads.

A loop qualifies only when all of these hold. Otherwise it simply runs sequentially, which is still correct:

The last two rules mean no call can see the array while it's being filled. So create the array in the same function that fills it. An array passed in as a parameter disqualifies the loop, and so does a function that fills its argument, which isn't parallel-safe anyway. --trace shows each parallel map as it runs, with its line number and batch count; --ast shows how the loop was rewritten (src/dolphin/src/fill.hpp explains the rewrite).

A comprehension, out = [decode_record(buf, o) for o in offsets], gets the same parallel map with less code. Use the fill form when the index isn't just the position in a list, when filling a dict, or when the array exists before the loop for other reasons.

The practical rule: keep parsing and decoding in pure functions that take text or bytes and return lists/dicts, and do all reading and printing in main. examples/metar.dol is built exactly that way.


11. Writing a parser for a NOAA text product #

Here are the idioms I'd use for a line-oriented or fixed-column NOAA file:

# noaa.dol: dolphin noaa.dol FILE

# Fixed-width columns: [start, end, name]. Slices clamp, so short lines give "".
COLUMNS = [[0, 4, "station"], [5, 11, "time"], [12, 18, "value"]]

def to_int(s):              # None for blank or missing fields instead of an exception
    t = s.strip()
    if t == "" or t == "M" or t == "MM":
        return None
    try:
        return int(t)
    except ValueError:
        return None

def to_float(s):
    t = s.strip()
    if t == "" or t == "M":
        return None
    try:
        return float(t)
    except ValueError:
        return None

def parse_line(line: str) -> dict:      # pure: runs in parallel over all lines
    r = {}
    for c in COLUMNS:
        r[c[2]] = line[c[0]:c[1]].strip()
    r["value"] = to_float(r["value"])
    return r

def is_data(line: str) -> bool:
    return line != "" and not line.startswith("#")

def main(path):
    text = read_file(path).decode()       # bytes -> str (DecodeError if not UTF-8)
    lines = [l.rstrip("\r") for l in text.split("\n")]
    data = [l for l in lines if is_data(l)]
    rows = [parse_line(l) for l in data]  # parallel map
    for r in rows:
        if r["value"] != None:
            print(f"{r['station']:<5} {r['time']:>6} {r['value']:8.2f}")
    print(f"{len(rows)} rows")
    return 0

Notes: