ycpp ships a Python package, also named ycpp. It copies the API of
pycrdt, the Python binding of Yrs. Code written for pycrdt runs
on ycpp after one line:
import ycpp as pycrdtUnder the hood the package drives the same C++ engine that C++ callers use. Its updates are plain Yjs v1 updates, so a ycpp document in Python syncs with pycrdt, Yjs, y-websocket and C++ ycpp.
There are three layers:
python/ycpp/*.py, pure Python. The classes you use:Doc,Map,Text,Array, the XML types, transactions, events,UndoManager,SnapshotandStickyIndex. They follow pycrdt's class and method names. The sync messages,AwarenessandProviderare pycrdt's own Python code, adapted; they only call the document's public methods._ycpp, a compiled extension (python/src/_ycpp.cpp, built with nanobind). It converts Python values to ycpp'sAnyand back, holds the per-document lock, and queues events.- The C++ library. One
ycpp::Docper PythonDoc.
From a checkout, pip builds the extension with meson-python:
pip install .
pip install ".[test]" # adds pytest, hypothesis, pycrdt and the other test dependenciesYou need a C++23 compiler. Meson fetches nanobind and the other dependencies as wraps. The build
turns on -Dpython=enabled and -Dsimd=sse4.2 (see [tool.meson-python.args] in
pyproject.toml).
For a manual build in the tree:
meson setup builddir-py -Dpython=enabled
meson compile -C builddir-py
meson install -C builddir-pyCI builds wheels with cibuildwheel: CPython 3.11 to 3.15, plus the free-threaded 3.14t and 3.15t,
on Linux (manylinux_2_28, x86_64 and aarch64), macOS (x86_64 and arm64) and Windows (amd64).
Publishing them is a separate, manual step. Treat the Windows wheels as experimental for now.
The only runtime dependency is anyio, for the async parts (Doc.events(), Provider,
Awareness.start()), as in pycrdt.
from ycpp import Doc, Map, Text
a = Doc(client_id=1)
b = Doc(client_id=2)
notes = a.get("notes", type=Text)
settings = a.get("settings", type=Map)
with a.transaction(origin="setup"): # one update, one event
notes += "hello"
settings["gain"] = 0.5
# The whole document, applied to the other peer.
b.apply_update(a.get_update())
print(str(b.get("notes", type=Text))) # hello
print(b.get("settings", type=Map).to_py()) # {'gain': 0.5}
# Only what b is missing: send b's state vector, get the diff back.
notes += " world"
b.apply_update(a.get_update(b.get_state()))
print(str(b.get("notes", type=Text))) # hello world
# Live: forward every transaction of a to b.
subscription = a.observe(lambda event: b.apply_update(event.update))
settings["volume"] = 3
subscription.drop()apply_update raises ValueError("Cannot decode update") for malformed bytes. As in C++, the
document is left unchanged.
The surface follows pycrdt 0.14. The main pieces:
| Object | What it is |
|---|---|
Doc |
The document. client_id, guid, get_state(), get_update(state=None), apply_update(buf), transaction(origin=None), observe(cb), get(name, type=...), dict-style access to roots. skip_gc=True turns garbage collection off. |
Map, Array, Text |
The shared types, with dict, list and string protocols. Text adds insert, insert_embed, format, diff(), apply_delta. |
XmlFragment, XmlElement, XmlText |
The XML types. |
MapEvent, ArrayEvent, TextEvent, XmlEvent |
Events, with keys, delta and path as pycrdt reports them. |
TransactionEvent |
What Doc.observe hands you: update, before_state, after_state. |
UndoManager |
Undo and redo, scoped to types and origins. |
Snapshot, Doc.from_snapshot |
Snapshots, and a document rebuilt as of one. Needs skip_gc=True. |
StickyIndex, Assoc |
Relative positions (see snapshots.md). |
Awareness |
y-protocols awareness, in Python. |
Provider, Channel |
pycrdt's websocket provider, over any transport. |
create_sync_message, handle_sync_message, ... |
The y-protocols sync helpers, as pycrdt names them. |
get_state, get_update, merge_updates |
The same work on update bytes, without a document. |
Callbacks may take zero, one (event) or two (event, transaction) arguments, as in pycrdt. An
exception raised in an observer is collected. When the outermost transaction ends, the collected
exceptions are raised together as an ExceptionGroup.
The extension takes care of locking:
- Free-threaded builds (3.14t, 3.15t). Each document has its own lock. Every call releases the GIL first, then takes the lock, so no thread ever blocks Python while it waits for a document. Events are queued during the call. Python callbacks run after the lock is released. That is why an observer can write back into the document it observes without deadlocking.
- GIL builds. With the GIL held, only one thread is inside a document anyway. The extension takes no extra lock and keeps the GIL.
- Two documents never block each other.
pycrdt's rule about transactions still applies, because the Python layer copies it. By default, a
with doc.transaction(): block opened while another thread has one open on the same document raises
RuntimeError("Already in a transaction"). Create the document with allow_multithreading=True to
let threads take turns instead; doc.new_transaction(timeout=...) then waits for its turn.
python/bench/torture_ft.py is the stress test: many threads doing random writes on shared
documents, with observers that write back. python/tests/test_threads.py runs in the normal suite.
ycpp follows Yjs where Yjs and pycrdt disagree. The differences a user may notice:
Bytes on the wire. Both sides read each other's updates. The bytes differ in a few places:
- Integers: ycpp writes them as varints, Yrs as floats. Both read back as the same Python value.
Like pycrdt, numbers read back as
float(1becomes1.0). - Binary values: ycpp writes binary content, Yrs writes an
Anyholding binary. Both read back asbytearray. - Client order: ycpp writes state vectors and delete sets with the highest client id first, as Yjs does. Yrs writes them ascending. The decoded content is the same.
Text positions. Positions count UTF-16 code units, as Yjs does. So Text.insert(2, "Ω") on
"héllo wörld" gives "héΩllo wörld", matching Yjs. pycrdt counts differently there and appends.
Formatting. Text.insert(i, "x") with no attributes inherits the formatting at i. Passing a
dict, even {}, replaces it. insert_embed never inherits, as in Yjs. pycrdt inherits on the embed
path too.
String embeds. insert_embed(i, "text") stores an embed, as pycrdt does. Yjs would insert plain
text there. This is the one place ycpp sides with pycrdt.
Concurrent inserts. Concurrent inserts at the same index can end up in a different order than in Yrs. Both orders are valid; ycpp's matches Yjs.
Writes from observers. An observer may write to the document it observes, even during
apply_update. pycrdt raises RuntimeError there. The write becomes a normal local change, and
reaches peers on the next sync.
Smaller things.
Text.apply_deltaandText.cleanup_formattingexist; pycrdt 0.14 only hasdiff().MapEvent.keyshas nooldValuewhen a nested map is deleted.- A detached
Map.to_py()returns a copy of its dict; pycrdt returns the dict itself. - Integers that do not fit a double raise
OverflowError; pycrdt panics. - Values nested deeper than
max_any_depth(32 levels by default) are refused. Python'sjsonhas no such limit, so a Python peer can build a value a ycpp peer refuses. Doc(doc=...), wrapping an existing low-level document, is not supported.Texthas no snapshot-based diff yet (the C++TextRef::to_delta(snapshot, prev)).
python/tests/pycrdt_suite is pycrdt 0.14.13's test suite, unchanged. Its conftest.py makes
import pycrdt load ycpp. It runs on its own:
pytest python/tests/pycrdt_suite -qThe tests it skips are listed in python/tests/pycrdt_suite/SKIPPED.md. They all reach pycrdt's
Rust internals (doc._doc, .integrated, create_transaction) or check a Rust-specific error
message, such as the lifetime of PyO3 borrowed views or "Object accessed from a different thread".
No other implementation could pass them. Nothing in the suite is marked as an expected failure.
apply_update()accepts any buffer (bytes,bytearray,memoryview) and reads it in place. It does not keep the buffer.get_update()andget_state()copy once, into the returnedbytes.