shmobj
English | Русский
Arbitrarily nested dict/list-like structures in shared memory (via mmap), accessible from multiple processes without
copying or deserialization.
shmobj provides the FrozenDict (Mapping) and FrozenList (Sequence) proxy objects for accessing data in shared
memory. The data is stored in memory only once. All processes access the same shared structure, and Python objects are
created only for the values that are actually accessed.
shmobj also provides mechanisms for sharing up-to-date data snapshots between processes:
shmobj.latest returns the latest snapshot published under a given name, and
shmobj.channel delivers new snapshots to subscribers (pub/sub).
Why shmobj?
CPU-bound Python workloads often use multiple processes to run computations in parallel and work around the GIL. Each process has its own memory space, so data loaded into each process is duplicated. For example, an 8-process workload using a 100 MB lookup table can consume around 800 MB.
shmobj solves this by storing the data once in shared memory. All processes access the same structure without copying or deserializing it.
But sharing data is only part of the problem: other processes also need to be notified when that data changes. Unlike
threads, processes do not share the same address space, so they cannot directly see changes in each other's memory.
Updates are typically sent through mechanisms such as multiprocessing.Queue, where data is serialized by the sending
process, transferred, and deserialized into a separate copy in the receiving process.
shmobj handles this too: the writer publishes a new snapshot once, and readers access it without copying — by name via
shmobj.latest or by subscription via shmobj.channel.
The measurements below refer to the shared dataset.
Memory usage
Dataset: one million records with the structure {"id", "name", "score", "tags": [...], "ok", "x"}. Each process iterated over the entire dataset.
| Processes | pickle — total memory |
shmobj — total memory |
|---|---|---|
| 1 | 628 MB | 168 MB |
| 4 | 2.5 GB | 168 MB |
| 8 | 5.0 GB | 168 MB |
Comparison with standard tools
This benchmark compares both access speed and memory usage. Four reader processes ran concurrently. Each attached to the dataset, performed 100,000 random d[k]["name"] lookups, and then iterated over all records.
Environment: Linux x86_64, 4 cores, Python 3.13.
Script: bench/compare.py.
| Approach | Reader attach | d[k]["name"] |
Full iteration | Total memory |
|---|---|---|---|---|
shmobj |
~50 µs | 1.3 µs | iter_values() 0.26 s, values() 0.74 s |
210 MB |
pickle + multiprocessing.shared_memory |
2.3 s | 1.0 µs | 0.07 s | 2.6 GB |
multiprocessing.Manager().dict() |
1 ms | 290 µs | ≈ 5 min ¹ | 690 MB |
fork + gc.freeze() |
— ² | 3.3 µs ³ | 0.3–0.4 s | 1.9 GB |
Total memory includes the storage itself (the shared-memory segment, pickle buffer, Manager server process, or parent process in the fork approach) as well as the readers' own memory, including approximately 10 MB per Python interpreter.
Notes:
- ¹ Estimated from 5,000 lookups. Each
d[k]requires an IPC request to the server process, followed by deserialization of the reply. - ² The parent process loads the data before
fork. Without a common parent process, this approach cannot share the dataset. - ³ Initial accesses trigger copy-on-write page duplication: about 330 MB per reader.
The trade-off for storing a single shared copy is slower access: a key lookup is 3–6 times slower than in a regular dict, while a full iteration is about 4 times slower with iter_values() and 11 times slower with values().
For workloads with frequent access, use the faster methods: get_many(), iter_values(), iter_items(), and materialize().
More: Access speed, comparison with alternatives, measurements.
The detailed documentation in doc/ is currently available in Russian.
Installation
pip install shmobj
Prebuilt wheels are available for:
- Python: CPython 3.11 and later;
- Linux: x86_64, aarch64 — glibc (manylinux) and musl (musllinux, Alpine);
- Windows: x64;
- macOS: arm64, x86_64 — partial support (limitations).
On other platforms, pip builds the package from the source distribution (sdist), which requires Rust (building from source).
The same wheels are available on the releases page:
pip install ./shmobj-<version>-cp311-abi3-<platform>.whl
Main use cases
| Use case | API | Example |
|---|---|---|
| Share one dataset across multiple processes | create() / attach() |
shared_pool.py |
| Let readers access the latest published snapshot | shmobj.latest |
latest_pubsub.py |
| Receive new snapshots without polling | shmobj.channel |
channel_pubsub.py |
Read data from a file or bytes |
dumps() / loads() |
file_mmap.py |
All examples are in the examples directory.
Install shmobj before running them.
Shared dataset
create() creates a segment and writes the data structure to it. Other processes attach to the segment by name using
attach(). The memory is released after unlink() has been called and all processes have closed the segment (on Windows,
after the last handle is closed).
import shmobj
# Writer process
segment = shmobj.create({
"users": [
{"id": 1, "name": "Ann", "score": 42},
{"id": 2, "name": "Bob", "score": 37},
]
})
print(segment.name) # pass the name to the reader processes
# Reader process
with shmobj.attach(segment.name) as segment:
users = segment.root["users"]
print(users[0].get_many(["id", "name"]))
total = sum(user["score"] for user in users.iter_values())
FrozenDict and FrozenList implement the Mapping and Sequence interfaces, so you can use them much like regular
dict and list objects.
It also works with multiprocessing (shared_pool.py):
import multiprocessing
import shmobj
def init(segment_name):
global users
users = shmobj.attach(segment_name).root["users"] # The proxy keeps the segment open for the lifetime of the worker.
def score(index):
return users[index]["score"]
if __name__ == "__main__":
data = {"users": [{"id": i, "score": i % 100} for i in range(100_000)]}
# Exiting the with block closes the segment and unlinks it from the OS.
with shmobj.create(data, unlink_on_close=True) as segment:
with multiprocessing.Pool(4, initializer=init, initargs=(segment.name,)) as pool:
print(sum(pool.map(score, range(len(data["users"])), chunksize=10_000)))
shmobj.latest
shmobj.latest lets you publish snapshots under a given name. The writer publishes a new snapshot in place of the
previous one, and readers get the current version by calling get(). No sockets are involved, and processes can start
in any order.
from shmobj import latest
# Writer process
writer = latest.Writer("metrics")
writer.put({"vms": {101: {"cpu": 0.5}}})
# Reader process
reader = latest.Reader("metrics")
root = reader.get() # None if no snapshot has been published yet; otherwise, the same object until it changes
As long as the snapshot remains unchanged, get() returns the same object. A reader only detects an update when it calls
get() again.
Example: latest_pubsub.py.
Cleanup after a crash. On Linux and macOS, segment names may remain registered with the OS if the writer crashes.
On Linux, these segments are located in /dev/shm. They remain there until a reboot, a container restart, or the next
writer that uses the same name.
Pub/Sub: shmobj.channel
One writer, multiple readers. Readers are notified of new snapshots without polling.
- A new subscriber immediately receives the latest snapshot.
- Intermediate snapshots may be skipped: readers get the current state, not a queue of every update.
- After all processes exit, the OS releases the channel resources; no names are left behind in
/dev/shmeither. - The channel address remains stable, so readers can reconnect after the writer restarts.
On Linux, an address such as "\0name" uses the abstract Unix socket namespace. It is not a file, and the kernel releases
the address when the writer exits. Windows uses TCP loopback instead.
Synchronous API
import itertools
import sys
import time
from shmobj import channel
ADDRESS = ("127.0.0.1", 50555) if sys.platform == "win32" else "\0shmobj-example"
# Writer
with channel.Publisher() as pub:
pub.accept_in_thread(channel.listen(ADDRESS)) # a background thread accepts subscribers
for tick in itertools.count():
pub.publish({"tick": tick, "vms": {101: {"cpu": tick % 100}}}) # non-blocking
time.sleep(1)
# Reader:
while True:
# wait until the writer starts listening; wait_writer=30 — at most 30 seconds
with channel.Subscriber(channel.connect(ADDRESS, wait_writer=True)) as sub:
while sub.wait(): # True — a snapshot arrived; False — the writer closed or crashed
print(sub.latest["vms"][101]["cpu"]) # FrozenDict backed by shared memory
Example: channel_pubsub.py.
asyncio API
The channel supports asynchronous connections and waiting for updates. Waiting for the writer does not block the event loop.
import asyncio
import itertools
import sys
from shmobj import channel
ADDRESS = ("127.0.0.1", 50555) if sys.platform == "win32" else "\0shmobj-example"
# Writer
async def main():
with channel.Publisher() as pub:
pub.accept_in_loop(channel.listen(ADDRESS)) # the event loop accepts subscribers, without a separate thread
for tick in itertools.count():
pub.publish({"tick": tick, "vms": {101: {"cpu": tick % 100}}})
await asyncio.sleep(1)
# Reader:
async def main():
while True:
sock = await channel.connect_async(ADDRESS, wait_writer=True) # waiting does not block the event loop
with channel.Subscriber(sock) as sub:
while await sub.wait_async():
print(sub.latest["vms"][101]["cpu"])
# Reader with a callback: called in the event loop for each new snapshot
def on_snapshot(root):
print(root["vms"][101]["cpu"])
async def main():
sock = await channel.connect_async(ADDRESS, wait_writer=True)
with channel.Subscriber(sock) as sub:
sub.attach(on_snapshot) # calls on_snapshot(sub.latest) for each new snapshot
while await sub.wait_async(): # also works with a callback; False — the writer closed or crashed
pass
Example: channel_pubsub_async.py.
Synchronous and asynchronous writers and readers are compatible. For example, an asyncio reader can connect to a synchronous writer.
Files, bytes and mmap
dumps() creates a buffer in the shmobj format, and loads() opens the structure directly from a supported buffer
(bytes, mmap, or another supported type) without copying the underlying data. When multiple processes read the same file, the OS
serves its pages from the shared file cache.
import mmap
import shmobj
data = {"users": [{"id": 1, "name": "Ann", "score": 42}]}
# Save the structure to a file.
with open("data.shmobj", "wb") as file:
file.write(shmobj.dumps(data))
with open("data.shmobj", "rb") as file: # in each process, file pages come from the shared OS cache
root = shmobj.loads(mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ))
Segment lifecycle
close()closes the segment in the current process.unlink()removes the segment's name from the OS. Exiting awithblock callsclose(). Automaticunlink()is performed only for segments created withunlink_on_close=True.- Proxy objects keep the segment open. Accessing them after
close()raisesSegmentClosedError. - Linux and macOS: a segment is a POSIX shared memory object. On Linux, it is represented by a file in
/dev/shmand stored in RAM. The segment exists untilunlink()is called, not merely until its creator exits. - Windows: the segment is removed after the last handle is closed.
If the entire process group crashes on Linux or macOS, the segment name remains registered with the OS until a reboot
(or a container restart), or until you run rm /dev/shm/<name> on Linux.
More: Segment lifecycle.
Limitations
- Read-only access. Published data cannot be modified in place. To update it, publish a new snapshot via
shmobj.latestorshmobj.channel. - Supported values:
dict,list,tuple(represented as a list when read),None,bool, arbitrary-precisionint,float,strandbytes. Dictionary keys must be scalar values. - macOS — partial support:
shmobj.channelis not available (useshmobj.latestinstead). The package passes the test suite but has not been used in production projects. - Format validation: accessing corrupted data raises
FormatError.validate()checks the entire buffer. - Docker: by default, each container has its own
/dev/shm(64 MB) and its own network. You can work around this by configuring shared IPC andshm_sizein Compose, or by using a channel over a socket file in a shared volume — Docker.
Why not use Python's standard tools?
multiprocessing.shared_memory. It provides a shared byte buffer, but has no built-in support for nested Python structures. You must serialize the structure (for example, withpickle), and each process then deserializes it into its own copy.multiprocessing.Manager().dict(). The data is managed by a separate server process. Accessing a dictionary item requires an IPC request and serialization.fork. By itself, it does not guarantee memory savings for Python objects: reference-count updates can trigger copy-on-write, causing memory pages to be copied between processes.
More: Comparison with alternatives.
Documentation
- Guide — segments, files, data validation,
channel,latest, Docker and the debugger. - API Reference — the public API.
- Build — wheel layout and portable builds.
- Data format and architecture — the binary format and internal design.
- Development — development environment, checks and repository layout.
- Measurements and project status.
Building from source
Quick install from Git
Install directly from the repository (pip downloads maturin and builds the wheel; Rust is required):
pip install git+https://github.com/Aleksandrln/shmobj
Full build from a project checkout
Requires CPython 3.11+ and stable Rust (rustup). On Windows, you also need Visual Studio Build Tools with the C++ component. Install Rust on Linux and macOS with:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
To build a wheel from a local checkout, install maturin in a virtual environment (Debian and Ubuntu block pip install
outside a virtual environment under PEP 668):
git clone https://github.com/Aleksandrln/shmobj
cd shmobj
python3 -m venv .venv
. .venv/bin/activate # Windows: .venv\Scripts\activate
pip install maturin
maturin build --release -o dist # dist/shmobj-<version>-cp311-abi3-<platform>.whl
maturin sdist -o dist # source distribution
The wheel can be installed in any CPython 3.11+ environment on the same platform: pip install dist/shmobj-*.whl.
Without --release, the build is about 10 times slower. cargo build --release builds only the library, not the
Python package.
Wheel layout and portable builds (older glibc, Windows builds from Linux): doc/build.md.
License
Dual-licensed under MIT or Apache-2.0, at your option.
Author
Created by AleksandrLn with the help of Claude by Anthropic.
Metadata
Release files for shmobj 0.1.5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| shmobj-0.1.5.tar.gz | 71.2 kB | With provenance | Details for shmobj-0.1.5.tar.gz |
Built distributions (wheels)
Total release size: 2.9 MB
Release files / shmobj-0.1.5.tar.gz
| Download URL | shmobj-0.1.5.tar.gz |
|---|---|
| Size | 71.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0bc43002730db8df599dd0414ab757b77405e957c11796ab26f2d24dd8cd0e31
|
|
BLAKE2b-256 checksum How to use checksums |
31f30671447169f449d8fbaac642b6781d54bea071bf15a816a9918b7582e709
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / shmobj-0.1.5-cp311-abi3-win_amd64.whl
| Download URL | shmobj-0.1.5-cp311-abi3-win_amd64.whl |
|---|---|
| Size | 251.8 kB |
| Tags | CPython 3.11 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
4a975d89ca4c764af7825021e99ddb65f478a1a0a460275d44b4e48ad2744588
|
|
BLAKE2b-256 checksum How to use checksums |
5b237a202b61cbcf2fd8e9164be878bebb27283c8d2e7ed31a905ea00749b913
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / shmobj-0.1.5-cp311-abi3-musllinux_1_2_x86_64.whl
| Download URL | shmobj-0.1.5-cp311-abi3-musllinux_1_2_x86_64.whl |
|---|---|
| Size | 574.1 kB |
| Tags | CPython 3.11 Linux musl 1.2+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
4759eb4a0f777aaaab4eaa06f7a3f29067d10a8cb84e3c1617c880bb4ffd03d5
|
|
BLAKE2b-256 checksum How to use checksums |
8c7c593b5933763b41262437240c268b1c31eaf520a3a0aa654b4e235f63d7d9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / shmobj-0.1.5-cp311-abi3-musllinux_1_2_aarch64.whl
| Download URL | shmobj-0.1.5-cp311-abi3-musllinux_1_2_aarch64.whl |
|---|---|
| Size | 539.4 kB |
| Tags | CPython 3.11 Linux musl 1.2+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
e236ce7313000ed17aed8b2b719b153b3d23c704c6522e097f219880d8a99052
|
|
BLAKE2b-256 checksum How to use checksums |
b3494da40ee5d2d4f1daa03bc89ed2ac39fd9b9e44ffbf6c0407e50e8b312911
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / shmobj-0.1.5-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
| Download URL | shmobj-0.1.5-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl |
|---|---|
| Size | 362.9 kB |
| Tags | CPython 3.11 Linux glibc 2.17+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
f34a0edef0bcac36972c8d297e4e64656bbf330d75d74f1f3efd79636dd4a7a9
|
|
BLAKE2b-256 checksum How to use checksums |
ce1ff1ffa2844eaee905cdb9ae3116f1a151b405d0cdc7b42b738caf7f35cbcd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / shmobj-0.1.5-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
| Download URL | shmobj-0.1.5-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl |
|---|---|
| Size | 361.9 kB |
| Tags | CPython 3.11 Linux glibc 2.17+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
f8c509a76ab4aecd4fa08f9807f692fbae9dd530675212ab2a4aefaeca15e62f
|
|
BLAKE2b-256 checksum How to use checksums |
7200eb973fe3b17c9a00ce153d832fa918f9a9d92f63a586693e64e5f0aa3f49
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / shmobj-0.1.5-cp311-abi3-macosx_11_0_arm64.whl
| Download URL | shmobj-0.1.5-cp311-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 341.3 kB |
| Tags | CPython 3.11 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
d8d7dbd5bc045409f12dc45d5f1c8a1bb638a2b37472d6f3dc037a1d8521e3be
|
|
BLAKE2b-256 checksum How to use checksums |
accf74b7e4937b3d95dddf761181a1f6713e823334e3db5ae87c0185f31f68b1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / shmobj-0.1.5-cp311-abi3-macosx_10_12_x86_64.whl
| Download URL | shmobj-0.1.5-cp311-abi3-macosx_10_12_x86_64.whl |
|---|---|
| Size | 348.1 kB |
| Tags | CPython 3.11 abi3 macOS 10.12+ x86-64 |
|
SHA-256 checksum How to use checksums |
89b983c1b8946aea28f094df7c52c5565f55c7c05bb283a0523d8e144789c1d2
|
|
BLAKE2b-256 checksum How to use checksums |
c43b23649ea70360f084ab4d28ea35f990f9ff6ce9bbde5fdb0658a453f42481
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logSecurity for shmobj 0.1.5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 8 files in this release have been uploaded with provenance metadata.
Attestation for shmobj-0.1.5.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.