On this page
  1. copyreg
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. When to Use copyreg vs. __reduce__
  7. Gotchas & Boundaries
  8. Common Functions

copyreg

Prev: copy | Up: stdlib_module | Next: csv
Rel: pickle, shelve, marshal, dbm, sqlite3
Ref: docs.python.org — copyreg
Tags: #public #python3 #stdlib


Import

import copyreg

Overview

Registry for custom pickle and copy reduction hooks (copyreg.pickle(), copyreg.constructor(), copyreg.add_extension()). Use copyreg when you need to make a third-party class or C extension type picklable without modifying its class definition (i.e., when you can't add __reduce__ directly to the class).

Quick Start

import copyreg
import pickle

class Point:
    def __init__(self, x: int, y: int) -> None:
        self.x, self.y = x, y

def pickle_point(p: Point):
    return (Point, (p.x, p.y))

copyreg.pickle(Point, pickle_point)
restored = pickle.loads(pickle.dumps(Point(3, 4)))
assert (restored.x, restored.y) == (3, 4)

Implementation Walkthrough

1. When to Use copyreg vs. __reduce__

Gotchas & Boundaries

Common Functions

Linked from

Related notes