python / python/cpython

Add copyreg.copy() and copyreg.deepcopy()

Open
#153,612 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

Proposal:

Add two registration functions to copyreg, following the copyreg.pickle() precedent:

  • copyreg.copy(type, function) — registers the shallow copy function for objects of type type; called as function(obj), like __copy__.
  • copyreg.deepcopy(type, function) — registers the deep copy function; called as function(obj, memo), like __deepcopy__.

copy.copy() and copy.deepcopy() use the registered functions in preference to the special methods and the pickle interfaces. Registration is by exact type and does not affect pickling. This allows customizing copying of instances of types that cannot be modified — for example, treating an external library's immutable objects as atomic:

copyreg.deepcopy(thirdparty.Handle, lambda obj, memo: obj)

Today the only way to customize copying of a foreign type is copyreg.pickle(), which forces copy and pickle semantics to be the same. The private _copy_dispatch and _deepcopy_dispatch tables have been monkey-patched in the wild for lack of a public API — even by our own test_descr. The new registries replace this non-public way; _deepcopy_dispatch is now removed, as _copy_dispatch already was in gh-128118.

This was requested in gh-141737. Implementation is ready; PR to follow.

Has this already been discussed elsewhere?

Companion of PEP 837, whose Rationale notes that registries for other protocols will be proposed separately: https://discuss.python.org/t/pep-837-extensible-json-serialization/108124

Links to previous discussion of this feature:
  • gh-141737 — the direct feature request
  • gh-128118 — removal of the historical _copy_dispatch table
Linked PRs
  • gh-153613

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the copyreg.copy() and copyreg.deepcopy() proposal alongside the copy.copy() and copy.deepcopy() entry points. Review linked PR gh-153613 and verify that exact-type registrations take precedence over special methods and pickle interfaces, while copying remains separate from pickling.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.