capnproto-1.0 (>=0.8.0 will also work if linking to system libraries)
Not necessary if using bundled capnproto
Python development headers (i.e. Python.h)
Distributables from python.org include these, however they are usually in a separate package on Linux distributions
32-bit Linux requires that capnproto be compiled with -fPIC. This is usually set correctly unless you are compiling canproto yourself. This is also called -DCMAKE_POSITION_INDEPENDENT_CODE=1 for cmake.
pycapnp has additional development dependencies, including cython and pytest. See requirements.txt for them all.
Building and installation
Install with pip install pycapnp. You can set the CC environment variable to control which compiler is used, ie CC=gcc-8.2 pip install pycapnp.
Or you can clone the repo like so:
git clone https://github.com/capnproto/pycapnp.git
cd pycapnp
pip install .
By default, the setup script will automatically use the locally installed Cap'n Proto.
If Cap'n Proto is not installed, it will bundle and build the matching Cap'n Proto library.
To enforce bundling, the Cap'n Proto library:
pip install . -C force-bundled-libcapnp=True
If you wish to install using the latest upstream C++ Cap'n Proto:
To enforce using the installed Cap'n Proto from the system:
pip install . -C force-system-libcapnp=True
The bundling system isn't that smart so it might be necessary to clean up the bundled build when changing versions:
python setup.py clean
Stub-file generation
While not directly supported by pycapnp, a tool has been created to help generate pycapnp stubfile to assist with development (this is very helpful if you're new to pypcapnp!). See #289 for more details.
To test, use a pipenv (or install requirements.txt and run pytest manually).
pip install pipenv
pipenv install
pipenv run pytest
Binary Packages
Building a Python wheel distributiion
pip wheel .
Releasing to PyPI
Wheels and the sdist are built by the Build GitHub Actions workflow
(.github/workflows/wheels.yml) for every push, including tag pushes. The
scripts/release-pypi.sh helper downloads those artifacts for a given tag (or
explicit run ID) and uploads them to PyPI via twine.
Typical release flow:
git tag v2.2.1
git push origin v2.2.1
# wait for the "Build" workflow run to finish successfully on GitHub
# Download artifacts and upload to PyPI (creates dist_221/ by default).
scripts/release-pypi.sh v2.2.1
# Or, target a specific Actions run id:
scripts/release-pypi.sh 1234567890
# Dry run: upload to TestPyPI (https://test.pypi.org) instead of real PyPI.
# Useful for validating the release flow end-to-end before pushing to
# production. Requires a TestPyPI account + API token configured in
# ~/.pypirc under a [testpypi] section. See
# https://packaging.python.org/en/latest/guides/using-testpypi/ .
scripts/release-pypi.sh v2.2.1 --test
Requirements on the release machine:
gh CLI, authenticated (gh auth login)
python3 (the script creates .venv-release/ and installs twine into it)
PyPI credentials available to twine, e.g. TWINE_USERNAME=__token__ and
TWINE_PASSWORD=<api-token>, or a configured ~/.pypirc
The script:
Resolves the latest successful wheels.yml run for the tag (or uses the
given run ID).
Downloads cibw-* artifacts and flattens all *.whl / *.tar.gz files
into the output directory (default dist_<digits> for tags,
dist_run_<id> for run IDs; pass a second arg to override, and --force
to reuse a non-empty directory).
Runs twine check, prints the file list, and prompts before running
twine upload.
Make sure to look at the examples. The examples are generally kept up to date with the recommended usage of the library.
The examples directory has one example that shows off pycapnp quite nicely. Here it is, reproduced:
import os
import capnp
import addressbook_capnp
def writeAddressBook(file):
addresses = addressbook_capnp.AddressBook.new_message()
people = addresses.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhones = alice.init('phones', 1)
alicePhones[0].number = "555-1212"
alicePhones[0].type = 'mobile'
alice.employment.school = "MIT"
bob = people[1]
bob.id = 456
bob.name = 'Bob'
bob.email = 'bob@example.com'
bobPhones = bob.init('phones', 2)
bobPhones[0].number = "555-4567"
bobPhones[0].type = 'home'
bobPhones[1].number = "555-7654"
bobPhones[1].type = 'work'
bob.employment.unemployed = None
addresses.write(file)
def printAddressBook(file):
addresses = addressbook_capnp.AddressBook.read(file)
for person in addresses.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
which = person.employment.which()
print(which)
if which == 'unemployed':
print('unemployed')
elif which == 'employer':
print('employer:', person.employment.employer)
elif which == 'school':
print('student at:', person.employment.school)
elif which == 'selfEmployed':
print('self employed')
print()
if __name__ == '__main__':
f = open('example', 'w')
writeAddressBook(f)
f = open('example', 'r')
printAddressBook(f)
Also, pycapnp has gained RPC features that include pipelining and a promise style API. Refer to the calculator example in the examples directory for a much better demonstration:
import asyncio
import capnp
import socket
import test_capability_capnp
class Server(test_capability_capnp.TestInterface.Server):
def __init__(self, val=1):
self.val = val
async def foo(self, i, j, **kwargs):
return str(i * 5 + self.val)
async def client(read_end):
client = capnp.TwoPartyClient(read_end)
cap = client.bootstrap()
cap = cap.cast_as(test_capability_capnp.TestInterface)
remote = cap.foo(i=5)
response = await remote
assert response.x == '125'
async def main():
client_end, server_end = socket.socketpair(socket.AF_UNIX)
# This is a toy example using socketpair.
# In real situations, you can use any socket.
client_end = await capnp.AsyncIoStream.create_connection(sock=client_end)
server_end = await capnp.AsyncIoStream.create_connection(sock=server_end)
_ = capnp.TwoPartyServer(server_end, bootstrap=Server(100))
await client(client_end)
if __name__ == '__main__':
asyncio.run(capnp.run(main()))
Changelog
v2.2.4 (2026-07-03)
Fix memory leak in _DynamicCapabilityClient._send_helper() (#398)
Fix SIGSEGV (NULL pointer dereference) on malformed Text field
Update default bundled capnproto to 1.4.0
Migrate project dependency management, testing, and CI to uv
Consolidate configurations into pyproject.toml (removed Pipfile and requirements.txt)
Apply small ruff linting fixes
v2.2.3 (2026-05-30)
Fix test failures on Python 3.14 (#394)
Refine documentation for PyCustomMessageBuilder (#395)
Replace black and flake8 with ruff for linting and formatting
ci: deploy docs to gh-pages on tagged releases
Add scripts/release-pypi.sh for downloading CI artifacts and uploading to PyPI
v2.2.2 (2026-01-16)
Revert Data fields to bytes and add get_data_as_view for zero-copy access (#390)
Fix use-after-free in async write causing corruption with large payloads (#392)
Update macOS builds from 13 to 15 (#393)
v2.2.1 (2025-10-21)
Make message.to_dict() return bytes for DATA type field (#386)
v2.2.0 (2025-09-12)
Add binary support in dictionaries via base64 encoding (#351)
Remove installation dependency on cython. We now have no dependencies since libcapnp will automatically build as well.
v0.5.0 (2014-12-15)
Timer class capnp.getTimer()
pycapnp is now thread-safe and allows an event loop to be run in each thread
You must destroy and re-create the event loop to get this functionality (see test_threads.py)
Inheritance now works correctly for interfaces (previously inherited methods were inaccessible from pycapnp)
Add ability to import modules with dashes or spaces. Use underscores in place of them
from_bytes with builder=True is no longer zero copy. It never worked correctly, and is much safer now
Add num_first_segment_words argument wherever message creation can occur
Allow restoring a null objectId by passing None to restore
Support ordered dictionary in to_dict
Add ListSchema class and schemas for native types under capnp.types which completes all the Schemas needed to be wrapped. See test_schema.py for examples using it
Add automatic build of C++ libcapnp if it's not detected on the system. Also add flags --force-bundled-libcapnp and --force-system-libcapnp respectively
v0.4.6 (2014-9-10)
Fix build for new 0.21 release of Cython. 0.21 is now the minimum supported version of Cython.
v0.4.5 (2014-6-26)
Fix to_dict not converting enums to strings
v0.4.4 (2014-04-25)
Fix compilation problem with gcc 4.8
v0.4.3 (2014-02-18)
Fix problem with uninitialized unions in _from_dict
Add accesible version numbers for C++ libcapnp
v0.4.2 (2014-02-13)
Remove onDrained since it was removed upstream
Replace usage of strings as enum type with custom _DynamicEnum class.
Also change Struct.which() method to be a property Struct.which and return an enum type (_DynamicEnumField, which behaves much like _DynamicEnum).
TwoPartyServer.run_forever() now will handle more than 1 simulataneous connection.
Change exception wrapper to detect and raise AttributeError for field lookup exceptions (Fixes problem in Python3.x __dir__)
Allow setting of fields with python dicts.
0.4.1 (2013-12-18)
Remove python 3.2 from travis tests. Python 3.2 still should work fine, but it's more trouble than it's worth to write unicode tests that work in both it and Python2.
Fix problems with null characters in Text/Data fields. Fixes #19
0.4.0 (2013-12-12)
Initial working version of RPC
Add get_root_as_any to _MessageReader
Add capnp.pxd for public declarations of cython classes
Fix problems compiling with gcc4.7
v0.3.18 (2013-11-05)
Change naming of ReaderOption parameters to be pep8 compliant
v0.3.17 (2013-11-05)
Add ReaderOptions to read/read_packed/from_bytes
v0.3.16 (2013-10-28)
Add defaults flag to capnp-json. Also remove 'which' field
Add capnp-json serializer script. Also fix bugs in from_dict
Fix build for clang/python3. Also remove -fpermissive
Add as_builder method to Struct Reader
Add warning when writing the same message more than once
First working version of capability interfaces
Wrap InterfaceSchema
Fix setting string fields to support all types of strings
Fix changed API for DynamicObject/ObjectPointer
v0.3.15 (2013-09-19)
Add not having installed the C++ libcapnp library to 'Common Problems'
Add _short_str function for use in capnp_test_pycapnp.py
Add _DynamicStructBuilder.to_bytes() and .from_bytes()
Change == on StructSchema to return cbool
Add Builder and Reader ABCs for each struct type
v0.3.12 (2013-09-03)
Fix handling of empty path '' in load_module
Add from_dict
Fix bug in exception handling for which(). Also standardize exceptions.
Change import hook to require modules to end in '_capnp'
Add import monkey patch function.
Change naming for functions to conform to PEP 8. Also deprecate old read/write API
Update preferred method for reading/writing messages from files
v0.3.11 (2013-09-01)
Forgot to change project name in setup.py
v0.3.10 (2013-09-01)
Change all references to old project name (change from capnpc-python-cpp to pycapnp)
Change DynamicValue.Reader lists to be returned as _DynamicListReader
Unify setters for DynamicList and DynamicStruct
Add shortcuts for reading from / writing to files. In Python, it doesn't make much sense to force people to muck around with MessageReaders and MessageBuilders since everything is landing on the heap anyway. Instead, let's make it easy: MyType.read[Packed]From(file) reads a file and returns a MyType reader. MyType.newMessage() returns a MyType builder representing the root of a new message. You can call this builder's write[Packed]To(file) method to write it to a file.
Store Builders by value rather than allocate them separately on the heap (matches treatment of Readers). v0.3 fixes the bug that made this not work.
Wrap MessageBuilder::setRoot().
Add tests based on TestAllTypes from the C++ test.capnp. Fix problems uncovered in capnp.pyx.
Implement str and repr for struct and list builders. str uses prettyPrint while repr shows the type name and the low-whitespace stringification. Also implement repr for StructSchema, just because why not?
v0.3.9 (2013-08-30)
Change load to use a global SchemaParser. Make structs settable as field
Add docstrings for new functions and _DynamicResizableListBuilder
v0.3.8 (2013-08-29)
Add initial tests
Add _capnp for original Cython module. Meant for testing.
Lowercase schema so it conforms to member naming conventions
Expose _StructSchema's raw node
Add some useful _StructSchema, reader, and builder methods
Add full orphan functionality. Also, allow special orphan lists
Finish up adding docstrings to all public classes/methods
v0.3.7 (2013-08-26)
Add a ton of docstrings and add to official docs
Add DynamicOrphan
v0.3.6 (2013-08-26)
Add intersphinx for linking to python docs
Add C++ library version check
v0.3.5 (2013-08-25)
Add handling of constants in schemas
Fix new error with DynamicValue.Builder no longer being copyable
v0.3.4 (2013-08-22)
Fix Void namespace change
Updated capnp schema to conform with new union rules
v0.3.3 (2013-08-22)
Fix for the removal of DynamicUnion from the C++ API
v0.3.2 (2013-08-21)
Add MANIFEST.in to include README
v0.3.1 (2013-08-21)
Update docs with lines about upgrading setuptools
0.3.0 (2013-08-21)
Initial commit of docs
Add querying unnamed enums to structs
0.2.1 (2013-08-13)
Fix enum interface change for benchmark
Random formatting cleanup
Allow import paths in the schema loader
Add travis CI
0.2.0 (2013-08-12)
Initial working version
Alternatives
Use instead of pycapnp: tools that do the same job, closest first.