Skip to main content

pysafe-pickle

Safe, fast, schema-evolvable Python object graph serialization powered by Rust.

Documentation PyPI License GitHub stars

📖 Documentation: https://abdullah-masood-05.github.io/pygraph/

⭐ Enjoying pysafe-pickle? If it saved you from unsafe deserialization, please star it on GitHub or share it. It's free and it helps other Python developers find it.

What's New in v1.3.0

Performance

  • Faster than pickle — dumps is now faster than stdlib pickle on every benchmark shape; loads is on par or faster for most workloads
  • Dataclass serialization is 6x faster (dumps) and 22x faster (loads) for bulk dataclass payloads
  • String-heavy payloads serialize 2x faster

New Type Support

  • Arbitrary-precision integers (2**100, 10**1000, etc.)
  • bytearray (with identity/cycle preservation)
  • complex numbers
  • Strings with lone surrogates ("\ud800")

Bug Fixes

  • Dataclass self-referential cycles now load correctly
  • ClassVar and InitVar fields are no longer incorrectly serialized
  • Two dataclasses sharing a class name no longer corrupt each other's fields
  • Fields named self no longer break deserialization
  • loads() now accepts bytes, bytearray, and memoryview inputs

Features

  • Drop-in pickle API — dumps/loads/dump/load with the same signatures
  • Zero arbitrary code execution — no __reduce__ or __setstate__ calls during deserialization
  • Schema versioning — migration hooks for evolving your data models
  • Zero-copy tensor support — NumPy and PyTorch integration
  • Faster than pickle — Rust-powered serialization that beats stdlib pickle on most workloads
  • Extended type support — bytearray, complex, arbitrary-precision int, and surrogate strings
  • Pickle-compatible streaming — Pickler/Unpickler classes, PickleBuffer (PEP 574)
  • HMAC integrity — optional tamper detection on serialized data

Installation

pip install pysafe-pickle

For tensor support:

pip install pysafe-pickle[numpy]
pip install pysafe-pickle[torch]
pip install pysafe-pickle[all]

Quick Start

import pysafe_pickle as psp

# Serialize
data = {"key": "value", "numbers": [1, 2, 3]}
encoded = psp.dumps(data)

# Deserialize
decoded = psp.loads(encoded)
assert decoded == data

Schema Evolution

Define versioned dataclasses and register migrations:

from dataclasses import dataclass
import pysafe_pickle as psp

@dataclass
class User:
    name: str
    age: int
    email: str = ""
    __pysafe_pickle_version__ = 2

@psp.migrate(from_version=1, to_version=2, type_name="User")
def migrate_v1_to_v2(state: dict) -> dict:
    """V1 had 'name' + 'age', V2 adds 'email'."""
    state["email"] = ""
    state["__pysafe_pickle_version__"] = 2
    return state

How it works

  • Set __pysafe_pickle_version__ as a class attribute on your dataclass (legacy __pygraph_version__ is also fully supported)
  • Register migration functions with @psp.migrate(from_version=N, to_version=M, type_name="ClassName")
  • Migration functions receive a dict of the old state and return a dict with the new state
  • Chains of migrations are resolved automatically (e.g., v1 → v2 → v3)

Pickler / Unpickler

Use pickle-compatible streaming classes:

import pysafe_pickle as psp
import io

# Streaming dump
buf = io.BytesIO()
pickler = psp.Pickler(buf, protocol=5)
pickler.dump({"data": [1, 2, 3]})

# Streaming load
buf.seek(0)
unpickler = psp.Unpickler(buf)
result = unpickler.load()

Security

pysafe-pickle never calls __reduce__, __setstate__, or any arbitrary code during deserialization. Only allowlisted types can be loaded.

# Restrict deserialization to specific types
psp.loads(data, allowlist={"builtins.dict", "builtins.list"})

Allowlisted types

By default, pysafe-pickle supports:

Type Notes
None, bool, int, float Primitives
str, bytes Strings and binary
list, tuple Sequences
dict Mappings
set, frozenset Sets
dataclasses Any @dataclass instance

Any type not in this list raises UnsafeTypeError unless added to the allowlist.

Integrity verification

key = b"my-secret-key"
encoded = psp.dumps(data, hmac_key=key)
decoded = psp.loads(encoded, hmac_key=key)  # raises HMACError if tampered

Migration from v1.0.x (pygraph)

In v1.0.x, the package was imported as import pygraph. In v1.1.0:

  • The canonical import is now import pysafe_pickle as psp.
  • Zero code breaks: Existing code using import pygraph or from pygraph.migrations import migrate continues working identically via a backward-compatible shim, emitting a FutureWarning.
  • Binary compatibility: Files serialized with v1.0.x (magic PYGR) continue to deserialize seamlessly with zero warnings. New files are encoded with the PSPK magic header.
  • The pygraph shim will remain supported through v1.x and will be removed in v2.0.0.
# Legacy (deprecated in v1.1.0, emits warning, still works)
import pygraph
pygraph.dumps(data)

# Recommended
import pysafe_pickle as psp
psp.dumps(data)

Benchmarks

Run the benchmark suite to compare pysafe-pickle vs pickle:

uv run pytest benchmarks/ -v --benchmark-only

Development

# Install and build with uv / maturin
uv run maturin develop

# Run tests
cargo nextest run
uv run pytest tests/ -v

License

AGPL-3.0-only

Metadata

Release files for pysafe-pickle 1.3.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for pysafe-pickle 1.3.2
File Interpreter ABI Platform Actions
pysafe_pickle-1.3.2-cp310-abi3-win_amd64.whl CPython 3.10 abi3 Windows x86-64 Details for pysafe_pickle-1.3.2-cp310-abi3-win_amd64.whl
pysafe_pickle-1.3.2-cp310-abi3-manylinux_2_34_x86_64.whl CPython 3.10 abi3 Linux glibc 2.34+ x86-64 Details for pysafe_pickle-1.3.2-cp310-abi3-manylinux_2_34_x86_64.whl
pysafe_pickle-1.3.2-cp310-abi3-macosx_11_0_arm64.whl CPython 3.10 abi3 macOS 11.0+ ARM64 Details for pysafe_pickle-1.3.2-cp310-abi3-macosx_11_0_arm64.whl

Total release size: 740.5 kB

Release files / pysafe_pickle-1.3.2-cp310-abi3-win_amd64.whl

Download URL pysafe_pickle-1.3.2-cp310-abi3-win_amd64.whl
Size 183.6 kB
Tags CPython 3.10 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
325da3597ab5b3c09905e8d4e01d704e9c11ec21b97644e93b6f2852016b4e87
BLAKE2b-256 checksum
How to use checksums
b22f24fdece7a985c8b3ecf3fd290487aa67d8c76f5c231ae945fa8eb3f06a74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 11, 2026.

Transparency log

Release files / pysafe_pickle-1.3.2-cp310-abi3-manylinux_2_34_x86_64.whl

Download URL pysafe_pickle-1.3.2-cp310-abi3-manylinux_2_34_x86_64.whl
Size 286.3 kB
Tags CPython 3.10 Linux glibc 2.34+ x86-64 abi3
SHA-256 checksum
How to use checksums
467a8d5fc319937a58660bd7b9a37f822d96def0042c50ea3b5e03b615153196
BLAKE2b-256 checksum
How to use checksums
f3e1b2efa4cb0163cb65e8e6fa730cd9ca97d3137bbc41d97d7f45383d7badd1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 11, 2026.

Transparency log

Release files / pysafe_pickle-1.3.2-cp310-abi3-macosx_11_0_arm64.whl

Download URL pysafe_pickle-1.3.2-cp310-abi3-macosx_11_0_arm64.whl
Size 270.6 kB
Tags CPython 3.10 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
0fbdbabb69ab9982f9159e8083ab875831dc0255f47204d3fd8480bd5381a35e
BLAKE2b-256 checksum
How to use checksums
fb7df6f5130d7451b92cdeb1a2b360d91dc20558d7972345ec2a16d6e19506e5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 11, 2026.

Transparency log

Security for pysafe-pickle 1.3.2

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 3 files in this release have been uploaded with provenance metadata.

Select from 3 files

Attestation for pysafe_pickle-1.3.2-cp310-abi3-win_amd64.whl

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 Oct 11, 2026.

Transparency log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page