Skip to content

Comments

feat: add __replace__ to BaseContainer for copy.replace support#2345

Closed
TheAbMehta wants to merge 2 commits intodry-python:masterfrom
TheAbMehta:feat/add-replace-support-for-copy-replace
Closed

feat: add __replace__ to BaseContainer for copy.replace support#2345
TheAbMehta wants to merge 2 commits intodry-python:masterfrom
TheAbMehta:feat/add-replace-support-for-copy-replace

Conversation

@TheAbMehta
Copy link

@TheAbMehta TheAbMehta commented Feb 21, 2026

Summary

Add __replace__ magic method to BaseContainer so that Python 3.13's copy.replace() works with all container types (Maybe, Result, IO, etc.).

Details

Python 3.13 introduced copy.replace() (PEP 618, docs) which delegates to __replace__(**kwargs) on the target object. This PR adds that protocol to BaseContainer.

Usage:

import copy
from returns.maybe import Some

original = Some(1)
replaced = copy.replace(original, inner_value=2)
assert replaced == Some(2)

Implementation:

  • Accepts inner_value as the only valid keyword argument
  • Returns a new container of the same type with the given inner value
  • Raises TypeError for unrecognised field names
  • Works on all Python versions via __replace__() directly; copy.replace() integration requires 3.13+

Tests:

  • __replace__ with a new value
  • __replace__ with no kwargs (identity)
  • Rejection of unknown fields
  • copy.replace integration (skipped below 3.13)

The CI matrix already includes Python 3.13, so that part of #1920 is already done.

Closes #1920

Disclosure

This PR was authored with the assistance of Claude (LLM) to help understand the codebase and structure the implementation and description.

…on 3.13+)

Add the __replace__ magic method to BaseContainer so that
copy.replace(container, inner_value=new_val) creates a new container
of the same type with the given inner value.

The method accepts a single keyword argument 'inner_value' and raises
TypeError for any unrecognised fields, following the copy.replace protocol
introduced in Python 3.13 (PEP 618).

Tests cover the dunder method directly (all Python versions), the
copy.replace integration (skipped below 3.13), no-arg identity, and
the rejection of unknown fields.

Closes #1920 (partial — CI matrix already includes 3.13)
- Remove explicit positional index in format string (UP030)
- Avoid direct dunder calls in tests by using a bound reference (PLC2801)
@TheAbMehta TheAbMehta closed this Feb 22, 2026
@TheAbMehta TheAbMehta deleted the feat/add-replace-support-for-copy-replace branch February 22, 2026 04:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Support copy.replace from 3.13

1 participant