Skip to content

Preserve subclass state when copying regular expression patterns - #182

Open
Mrun25 wants to merge 4 commits into
cpburnz:masterfrom
Mrun25:fix/pattern-shallow-copy
Open

Mrun25 wants to merge 4 commits into
cpburnz:masterfrom
Mrun25:fix/pattern-shallow-copy

Conversation

@Mrun25

@Mrun25 Mrun25 commented Nov 8, 2026

Copy link
Copy Markdown

Problem

copy.copy() reconstructs a RegexPattern through self.__class__(self.regex, self.include). This conflicts with the documented allowance for subclasses that do not accept include: copying such a subclass raises TypeError.

For subclasses that do accept those arguments, their constructor runs again. Any additional dictionary or slot state is reset instead of being shallow-copied. For example, a metadata list attached to a pattern is silently replaced by an empty list.

Change

Remove the constructor-based __copy__ override and let Python's standard copy protocol preserve the object's dictionary and slots without rerunning its constructor. This retains the concrete subclass, original pattern, compiled regex and include flag. Add tests for the built-in pattern classes, compiled flags, subclasses without include, and subclass dictionary, private-slot and unset-slot state. Update the changelog.

Validation

  • On the unchanged base, the five new tests report two failures and one error: subclass metadata resets and the single-argument constructor raises. With this change, all five pass.
  • Full unittest suite succeeds in CPython 3.9 through 3.15 and PyPy 3.9 through 3.12 base environments.
  • Full unittest suite succeeds in the separate Hyperscan and RE2 environments for each CPython version from 3.9 through 3.15, and in PyPy 3.10 with Hyperscan.
  • With both native backends installed on CPython 3.14, the full suite runs 325 tests successfully with one existing skip.
  • Mypy passes for pathspec, tests/check_usage.py and the new tests. Pyright passes for the same targets using the Python 3.14 environment.
  • Sphinx's warnings-as-errors documentation build, wheel/sdist build, Twine metadata checks and git diff --check pass.

Not verified: Windows/macOS, and the PyPy 3.11/3.12 Hyperscan environments. Those two environments lack prebuilt Hyperscan wheels here; their source builds did not complete within the local execution window. The base suites for both PyPy versions pass.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant