Nanuq 0.6 is the release the roadmap called "engine and edges". The engine part is Polars' streaming engine: queries that run in batches and write straight to files without holding the result in memory. The edges are the places where data enters and leaves: Arrow memory shared with other libraries (and with Nim code, without copying), Excel workbooks, SQLite databases, saved query plans, and two new column types for raw bytes and exact decimals.
It came in fourteen OpenSpec changes. Nine were planned; then the book ports and the go explainer asked for more, Pietro asked to build on the same Polars that py-polars 2.1 ships and to add cloud storage after all, and the new Polars coverage map turned up thirty small functions worth adding now. Two ideas from the plan did not make it, and the last section says why. Every snippet below runs, on a few made-up rows about bear sightings.
import std/[options, os, tables]
import nanuq
let tmp = getTempDir() / "designing-0-6"
createDir tmp
let sightings = newDataFrame:
bear: ["Ada", "Bo", "Ada", "Cy", "Bo", "Ada"]
region: ["north", "south", "north", "east", "south", "east"]
kg: [412.5, 380.0, 415.0, 290.5, 377.5, 418.0]
day: [1, 1, 2, 2, 3, 3]
echo sightings
shape: (6, 4) โโโโโโโโฌโโโโโโโโโฌโโโโโโโโฌโโโโโโ โ bear โ region โ kg โ day โ โ --- โ --- โ --- โ --- โ โ str โ str โ f64 โ i64 โ โโโโโโโโชโโโโโโโโโชโโโโโโโโชโโโโโโก โ Ada โ north โ 412.5 โ 1 โ โ Bo โ south โ 380.0 โ 1 โ โ Ada โ north โ 415.0 โ 2 โ โ Cy โ east โ 290.5 โ 2 โ โ Bo โ south โ 377.5 โ 3 โ โ Ada โ east โ 418.0 โ 3 โ โโโโโโโโดโโโโโโโโโดโโโโโโโโดโโโโโโ
1. One collect, with an engineโ contents
Python spells the engine as a string: lf.collect(engine="streaming"). Nanuq takes an
enum, Engine.Auto, Engine.Streaming or Engine.InMemory, as a second argument of
the collect we already had. A typo is a compile error, and the default stays the
one-argument collect. collectAll runs several queries together, so Polars can
share the parts they have in common.
There is no profile: py-polars 2.0 removed LazyFrame.profile, as its timings were
misleading under the streaming engine, and the Polars Nanuq now builds on (section 10)
no longer has it. Calling it is a compile-time error that says so.
let byBear = sightings.lazy.groupBy("bear").agg(col("kg").mean).sort("bear")
echo byBear.collect(Engine.Streaming)
shape: (3, 2) โโโโโโโโฌโโโโโโโโโโโโโ โ bear โ kg โ โ --- โ --- โ โ str โ f64 โ โโโโโโโโชโโโโโโโโโโโโโก โ Ada โ 415.166667 โ โ Bo โ 378.75 โ โ Cy โ 290.5 โ โโโโโโโโดโโโโโโโโโโโโโ
2. Sinks: a path or a PartitionBy, and lazy as a static flagโ contents
A sink writes a query's result to a file while it streams: sinkParquet, sinkIpc,
sinkCsv, sinkNdjson. Python's target is either a path or a PartitionBy object
that splits the output into Hive-style folders (region=north/...). Nanuq does the
same with a string | PartitionBy type class, so there is one proc per format, not two.
Python's sinks also take lazy=True, which returns the sink as a LazyFrame instead of
running it, so collect_all can run several sinks in one go. The return type depends
on the flag (nothing, or a LazyFrame), which a Nim proc can't do with a runtime bool.
So lazy is a static bool and the return type is auto: sinkCsv(path) is a
statement, sinkCsv(path, lazy = true) an expression.
sightings.lazy.filter(col("kg") > 400).sinkCsv(tmp / "heavy.csv")
echo readFile(tmp / "heavy.csv")
sightings.lazy.sinkParquet(PartitionBy(basePath: tmp / "by_region", key: @["region"]))
for kind, path in walkDir(tmp / "by_region", relative = true): echo path
bear,region,kg,day Ada,north,412.5,1 Ada,north,415.0,2 Ada,east,418.0,3 region=south region=east region=north
3. Saving a query planโ contents
serialize turns a LazyFrame (or an expression, via meta.serialize) into bytes or
JSON; deserialize turns it back. In Python the bytes are bytes. In Nanuq they are a
string, Nim's usual byte container, which writes to a file or a socket as is. The
format is SerializationFormat.Binary (Polars' compact format) or Json. As in Python,
a plan holds the data of in-memory frames, so a plan over scanParquet is small and a
plan over a DataFrame carries the rows with it.
The rest of the meta namespace came along: eq and ne (are two expressions the
same?), pop, isColumnSelection, isLiteral, isRegexProjection and treeFormat.
let plan = sightings.lazy.filter(col("bear") == "Ada").select("day", "kg")
let saved = plan.serialize(SerializationFormat.Json)
echo saved.len, " bytes of JSON"
echo LazyFrame.deserialize(saved, SerializationFormat.Json).collect
echo (col("kg") * 2).meta.eq(col("kg") * 2)
2854 bytes of JSON shape: (3, 2) โโโโโโโฌโโโโโโโโ โ day โ kg โ โ --- โ --- โ โ i64 โ f64 โ โโโโโโโชโโโโโโโโก โ 1 โ 412.5 โ โ 2 โ 415.0 โ โ 3 โ 418.0 โ โโโโโโโดโโโโโโโโ true
4. Bytes and decimalsโ contents
A Binary column holds raw bytes. A Nim string already is a byte sequence (it may
hold zeros and invalid UTF-8), so binary values go in and out as strings:
series("raw", @["\x00\x01", "ok"], Binary), and toList(string) reads them back. The
bin namespace has contains, startsWith, endsWith, encode, decode and
size; str.encode goes the other way.
Decimal(precision, scale) is an exact decimal type, for money and the like. Nim has
no decimal type in its standard library, so Nanuq reads decimal values as string
(exact) or float (convenient), and builds them by casting or with str.toDecimal.
A Decimal type prints as Nanuq code, Decimal(10, 2), like the other types since 0.5.
let prices = newDataFrame(series("price", @["12.50", "3.99", "100.00"]))
.select(col("price").str.toDecimal(2))
echo prices.schema
echo prices["price", 0, string]
echo newDataFrame(series("tag", @["polar"])).select(col("tag").str.encode(BinaryEncoding.Hex))
{"price": Decimal(38, 2)}
12.50
shape: (1, 1)
โโโโโโโโโโโโโโ
โ tag โ
โ --- โ
โ str โ
โโโโโโโโโโโโโโก
โ 706f6c6172 โ
โโโโโโโโโโโโโโ
5. Arrow memory, shared with Nimโ contents
Polars keeps each column in Arrow format. The Arrow C Data Interface is the standard
way to hand such a column to another library without copying it: two C structs, a
schema and an array, each with a release callback that frees it. Nanuq now speaks
it in both directions: toArrow/fromArrow for Series (Python's to_arrow and
pl.from_arrow), and an ArrowArrayStream for whole frames.
The Nim side has to answer one question: who frees the memory? We wrapped the two
structs in ArrowExport, an object with a destructor that calls release and a
=copy that is a compile error, so it can be moved but never freed twice. A consumer
that takes the array over sets its release to nil, as the Arrow spec says, and the
destructor then skips it.
The same machinery gives Nim code direct access to a column: view(T) returns a
ColumnView[T] over Polars' own buffer, with [], len, items and toOpenArray.
The type must match exactly (int for Int64, float32 for Float32) and the column
must have no nulls; otherwise view raises and points at toList. The view holds the
exported buffer, so it stays valid even if the Series goes away first.
let kg = sightings.view("kg", float)
var total = 0.0
for x in kg: total += x
echo kg.len, " values, total ", total
var ex = sightings.getColumn("day").toArrow
echo ex.schema.format, " ", ex.array.length
echo fromArrow(ex, name = "day again")
6 values, total 2293.5 l 6 shape: (6,) Series: 'day again' [i64] [ 1 1 2 2 3 3 ]
mapElements uses views when it can. In 0.5 each batch was copied into a Nim seq
and the results copied back; now a numeric column without nulls whose type matches the
proc's argument is read in place. On the 1,000,000-row benchmark in benchmarks/, the
int โ float callback went from 14-18 ms to 5 ms, against 2-4 ms for the native
expression and 128-187 ms for py-polars' map_elements. Strings and structs still
copy: they need a Nim string or object per value.
6. Excel without Pythonโ contents
Python Polars reads Excel through one of three Python packages (fastexcel, openpyxl, xlsx2csv) and writes it through XlsxWriter. Nanuq has no Python, so it uses two Rust crates compiled into the Nanuq library: calamine to read and rust_xlsxwriter to write. They add no system dependency and nothing to install.
readExcel(path, sheetName = "", sheetId = 1, hasHeader, headerRow, skipRows, columns, schemaOverrides) follows Python's names, with fastexcel's meaning: skipRows skips
rows after the header row, which the book found on a workbook with an empty row under
its header. Excel cells carry little type information,
so the column types are inferred: all booleans give Boolean, whole numbers Int64, other
numbers Float64, dates at midnight Date, other dates Datetime, anything else String.
schemaOverrides fixes the rest. readExcelSheets reads every sheet into an ordered
table (Python's sheet_id=0). writeExcel writes one sheet with a bold header, dates
formatted as dates and optional autofit, which covers the book's uses; XlsxWriter's
charts, conditional formats and tables are not there.
sightings.writeExcel(tmp / "sightings.xlsx", worksheet = "Sightings")
echo readExcel(tmp / "sightings.xlsx", sheetName = "Sightings").head(3)
shape: (3, 4) โโโโโโโโฌโโโโโโโโโฌโโโโโโโโฌโโโโโโ โ bear โ region โ kg โ day โ โ --- โ --- โ --- โ --- โ โ str โ str โ f64 โ i64 โ โโโโโโโโชโโโโโโโโโชโโโโโโโโชโโโโโโก โ Ada โ north โ 412.5 โ 1 โ โ Bo โ south โ 380.0 โ 1 โ โ Ada โ north โ 415.0 โ 2 โ โโโโโโโโดโโโโโโโโโดโโโโโโโโดโโโโโโ
7. SQLite, as an optional moduleโ contents
Python's read_database takes a connection from any of a dozen database libraries.
Nim's equivalent is db_connector, which covers SQLite, PostgreSQL and MySQL. We
started with SQLite, the one databases chapters use for examples, in an optional module
nanuq/database, so the core library does not depend on db_connector:
readDatabase(query, connection, schemaOverrides)andreadDatabaseUri(query, "sqlite:///path")read a query result. Column types come from the values (SQLite is dynamically typed), falling back on the declared column type.writeDatabase(df, tableName, connection, ifTableExists)creates the table and inserts the rows in one transaction, withIfTableExists.Fail,ReplaceorAppend(Python'sif_table_existsstrings).
import nanuq/database
import db_connector/db_sqlite
let db = open(tmp / "bears.db", "", "", "")
discard sightings.writeDatabase("sightings", db, IfTableExists.Replace)
echo readDatabase("SELECT bear, max(kg) AS kg FROM sightings GROUP BY bear ORDER BY bear", db)
db_sqlite.close(db)
shape: (3, 2) โโโโโโโโฌโโโโโโโโ โ bear โ kg โ โ --- โ --- โ โ str โ f64 โ โโโโโโโโชโโโโโโโโก โ Ada โ 418.0 โ โ Bo โ 380.0 โ โ Cy โ 290.5 โ โโโโโโโโดโโโโโโโโ
8. Testing helpersโ contents
polars.testing has assert_frame_equal and assert_series_equal, used by every test
suite that touches Polars. Nanuq's nanuq/testing has the same four procs in camelCase,
with Python's options (checkRowOrder, checkColumnOrder, checkDtypes, checkExact,
rtol, atol). On failure they raise AssertionDefect (what Nim's doAssert raises)
with the first difference, so unittest shows which column and row.
import nanuq/testing
try:
assertFrameEqual(sightings.head(2), sightings.tail(2))
except AssertionDefect as e:
echo e.msg
DataFrame column "bear" values differ at row 0: Ada != Bo
9. Smaller functions, and comparisons that keep their namesโ contents
The rest came from the book map, which lists the Polars functions each blocked book
section needs. The method spellings of operators (a.mul(2), a.sub(b)) exist because
the books chain them; xor, joinWhere (joins on inequalities), intRanges,
unstack, hist, rollingMap (with a typed Nim proc over each window), dtypeOf
and a dozen others unblock a section or two each. Frames got the aggregations Python
has on frames (df.mean, df.nullCount), group-bys got the shortcuts (g.sum,
g.head(2)), and for key, part in df.groupBy("bear") iterates over the groups.
One fix is worth a paragraph. Nim has no reflected operators like Python's __gt__ and
__lt__, so 0 < col("kg") called the overload with the literal on the left, and the
result column was named literal. Worse, all() > 0 (a selector) went through Nim's
> template, which rewrites it to 0 < all(), so every column came out as literal.
Now comparisons with a value on the left are mirrored (0 < x is x > 0), as Python's
reflected comparisons do, and all operators take selectors directly. Arithmetic is not
mirrored (1 + col("kg") is named literal), which is also what Python does.
echo sightings.select((col(float, int) > 2).name.suffix(" > 2")).head(2)
for key, part in sightings.groupBy("bear"):
echo key[0], ": ", part.height, " rows"
shape: (2, 2) โโโโโโโโโโฌโโโโโโโโโโ โ kg > 2 โ day > 2 โ โ --- โ --- โ โ bool โ bool โ โโโโโโโโโโชโโโโโโโโโโก โ true โ false โ โ true โ false โ โโโโโโโโโโดโโโโโโโโโโ Ada: 3 rows Bo: 2 rows Cy: 1 rows
10. The same Polars as py-polarsโ contents
Until 0.5 Nanuq used the newest Polars crate on crates.io. The Rust crates are released
by hand every few months, and the newest one, 0.55.2, matches py-polars 1.43, while the
book and the explainers compare against py-polars 2.1, about 940 commits later. Every
port found a few cells that differed for that reason alone: SQL table functions, hash
values, sampling order, Decimal mod.
So 0.6 builds Polars from the git tag py-2.1.0, the commit py-polars 2.1.0 was
released from. Two things a git dependency does not inherit had to be copied: the
workspace's [patch.crates-io] entries (forks of hashbrown, jemalloc and
color-backtrace) and the nightly toolchain the tag pins for release builds. The crate
version inside the tag still reads 0.55.1, so the tag, not the version, is what we
track. In exchange, Nanuq follows Polars 2: profile and cat.getCategories are gone,
CSV columns read without a header are column_0, column_1, ..., and topK and joins
without maintainOrder no longer promise an order. The spec examples caught each of
these.
The pin also showed something the old crate had hidden. Nanuq's DataFrame methods were
always df.lazy.<verb>.collect, and in Polars 2 a plain collect picks the streaming
engine. Python's DataFrame methods don't: they collect with the in-memory engine and
no plan optimizations, the "eager" flags. The two engines differ in small, visible
ways: the row order of a cross join or an unpivot, the count in a failed date parse
("1 out of 1 values" instead of "1 out of 3"). So DataFrame methods now collect the
way Python's do, and LazyFrame.collect keeps Python's default. The explainers and
the book, which print Nim and Python side by side, are what found it.
11. Cloud storageโ contents
The plan put cloud storage in 0.7, with the shared library, as "distribution". Then
the cost turned out to be tiny: Polars' streaming engine already compiles the object
store client, TLS and the async runtime into the library, and turning on S3, Google
Cloud Storage, Azure and HTTP adds about 2%. So every scan and read of CSV, Parquet,
IPC and NDJSON accepts a cloud URI, and they, the sinks and the writes take
storageOptions, the key/value pairs Python calls storage_options. Without them
Polars reads credentials from the environment, as in Python.
The one design question was writing. Polars' eager writers write local files; Python
routes a cloud write_parquet through a sink. Nanuq does the same, so
df.writeParquet("s3://bucket/x.parquet") just works. The tests run against a local
HTTP server and, in CI, a local S3 (moto).
echo isCloudPath("s3://polar-bears/census.parquet"), " ", isCloudPath(tmp / "x.parquet")
let toS3 = sightings.lazy.sinkParquet("s3://polar-bears/sightings.parquet", lazy = true,
storageOptions = {"aws_region": "eu-west-1"})
echo toS3 is LazyFrame # collecting it would upload the file
true false true
12. Thirty small functions from the coverage mapโ contents
The Polars coverage map, a new page of the site, lists every function of Python Polars
and whether Nanuq has it. Sorted by effort, it showed thirty that each take an hour or
two: empty frames (newDataFrame(schema = {...}), clear), isClose and the
null-aware eqMissing, business days, timeRange, cumulativeEval, matchToSchema,
mergeSorted, query optimization flags, IPC streams, readOds, table styles, and more.
Most are one bridge call on a Polars feature that was already compiled in; six needed
one more feature each. They went in as one change, so the map starts its 0.6 column
greener.
let empty = newDataFrame(schema = {"bear": String, "kg": Float64})
echo empty.isEmpty, " ", empty.columns
echo sightings.select(col("kg").isClose(415.0, absTol = 3.0).alias("about 415")).head(3)
true @["bear", "kg"] shape: (3, 1) โโโโโโโโโโโโโ โ about 415 โ โ --- โ โ bool โ โโโโโโโโโโโโโก โ true โ โ false โ โ true โ โโโโโโโโโโโโโ
What did not make itโ contents
- A formula macro. Datamancer writes
f{"kg" * 2}, and the plan proposed something similar. We dropped it: Polars expressions are already expressive, and if Nanuq gets Nim sugar for expressions it should be its own design, from cases where the method chains read badly. It is in the backlog as a design question. - Plotting. The book's plotting sections use
df.plot, which in Python is hvPlot or Altair. Nim's options are nim-plotly (used by the El Niรฑo explainer) and ggplotnim (throughtoDatamancer); both work today with a line of conversion. Aplotnamespace waits until we know which one to wrap. - A shared library. Shipping Nanuq as a dynamic library is about distribution, the theme of 0.7.
What's nextโ contents
The 0.6 explainer, Move 37, is a story about the game of go told with the new features. Then 0.7, "distribution": a shared library, leaner builds with only the Polars features you use, and the coverage groups still marked partial.