Skip to content

Thread safety

TL;DR

  • Narwhals objects are safe to share between threads for reading: methods return new objects; nothing mutates the receiver, nor the native object passed to from_native.
  • Writing is the backend's business: Narwhals has no in-place mutation API, but once you reach the native object (to_native, to_numpy, ...) the backend's rules apply.
  • DuckDB needs one connection per thread: the only backend with a rule that changes how you write Narwhals code, see DuckDB.

Tip

All of this holds on both the GIL-enabled and the free-threaded build. A race is a bug either way; free-threading just makes it likely enough to notice.

Global state inside Narwhals

State Thread-safe? Notes
Function caches
(backend_version, dtype conversions, plugin discovery, ...)
Yes lru_cache is threadsafe and the cached functions are pure,
so a concurrent cold cache costs at most a duplicated computation
Constant lookup tables
(dtype mappings, interval units, ...)
Yes Read-only after import
Configuration / registries / mutable singletons N/A Narwhals has none
narwhals.sql's DuckDB catalog Yes, per thread See narwhals.sql

Backend detection

Narwhals does not import your backend in order to recognise its objects: you must already have imported it to have an object to pass, so it looks the module up in sys.modules instead. Since a module is visible in sys.modules before its body finishes executing, Narwhals skips one that another thread is still importing: no object can come from it yet. It does import on your behalf when you name a backend (nw.from_dict(..., backend="pandas")) or convert between them (to_polars, to_arrow, ...), through a regular import, which Python already serializes across threads.

Sharing Narwhals objects

All of the following are safe to share between threads:

Object Why
DataFrame, LazyFrame, Series Every method returns a new object.
Lazily-cached metadata (schema, column names) is computed idempotently,
so a concurrent first access only repeats work
Expr A chain of immutable nodes. Expr.over copies before it rewrites,
so reusing one expression in several queries at once cannot corrupt it
GroupBy (the result of DataFrame.group_by(...)) Aggregation state is passed along the call, not stashed on the object
Schema A dict subclass: safe to read concurrently, but do not mutate a shared instance

Warning

Sharing is safe because nobody writes: if a worker hands the native object to something that mutates it in place, Narwhals' view goes stale too - from_native does not copy.

Backends

Backend Reads Writes to the native object
Polars Safe Operations return new objects, though immutability is not enforced
PyArrow Safe Arrow data is immutable
pandas Safe, except pandas < 3.1.1 on the free-threaded build:
concurrent reads of one frame can crash inside pandas
Not safe: from_native keeps the same object, so an in-place write (df.loc[...] = ...,
or into the NumPy buffer of .values / .to_numpy()) changes it under every reader, and can
race with them. Copy-on-write (the default since pandas 3.0) only protects other objects sharing the data
DuckDB One connection per thread, see below N/A
PySpark, SQLFrame, Ibis, Dask Delegated to the session / scheduler Consult the backend's own docs

DuckDB

Every thread needs its own .cursor(), a thread-local connection to the same database:

import duckdb
import narwhals as nw


def worker(con: duckdb.DuckDBPyConnection) -> None:
    cursor = con.cursor()  # one per thread
    lf = nw.from_native(cursor.sql("select * from my_table"))
    print(lf.filter(nw.col("a") > 1).collect())
  1. A cursor does not inherit LOCAL-scoped settings: TimeZone is one of them, so use SET GLOBAL, or set it on every cursor. It matters in Narwhals because DuckDB keeps the time zone in the connection rather than the dtype: collect_schema() reports a time-zone-aware column using the cursor's time zone.
  2. A relation belongs to the connection that created it: combining relations from two connections is rejected outright, so build frames you intend to join or concat in the thread that uses them.
  3. collect_schema() on frames from a shared connection is safe, executing on one is not: a time-zone-aware dtype is the one case where Narwhals queries your connection implicitly, and it serializes that query against its own calls only, so do not run your own queries on that connection meanwhile. Explicit execution (collect, to_arrow, ...) runs on the connection you gave it and follows DuckDB's rules.
  4. join_asof and unpivot on a file-backed or read-only database need duckdb-python >= 1.5.4: DuckDB has no relational-API equivalent for ASOF joins or UNPIVOT (duckdb#16980), so Narwhals runs them through DuckDBPyRelation.query, which registers a uniquely-named view on the relation's own connection. Since duckdb-python 1.5.4 that view goes to the temp catalog: it is scoped to the cursor and released when the cursor is closed. Older versions put it in the connection's current database, which a file-backed database would keep on disk and a read-only one rejects, so Narwhals raises NotImplementedError there instead. In-memory databases work on every version.

scan_csv and scan_parquet read through DuckDB's process-global default connection unless you pass connection=con.cursor().

narwhals.sql

narwhals.sql.table keeps a module-level DuckDB connection and gives each thread its own cursor on it. Since a cursor is a connection to the same database, the catalog is shared process-wide and name must be unique across threads; and by (2) above, tables created in different threads cannot be joined.

Free-threaded Python

Narwhals is pure Python with no compiled extensions, so importing it never re-enables the GIL. Whether your stack supports the free-threaded build depends on the backend: check that its wheels are built for cp314t (or whichever version you run).

CI covers it in two ways. On a free-threaded build, the suite runs again under pytest-run-parallel with --parallel-threads=4, which surfaces races through global state; it covers pandas and PyArrow only, until the other backends ship free-threaded wheels, and tests marked thread_unsafe run single-threaded. tests/free_threading_test.py stresses the guarantees on this page with its own thread pools; its DuckDB and Polars cases run in the regular (GIL-enabled) jobs. If you find a race, please open an issue with a script that reproduces it, ideally on a free-threaded build or with sys.setswitchinterval(1e-7).