Skip to content

Fix deepcopy for And, Or, and Not expressions#3295

Open
robreeves wants to merge 6 commits intoapache:mainfrom
robreeves:fix-deepcopy-apache
Open

Fix deepcopy for And, Or, and Not expressions#3295
robreeves wants to merge 6 commits intoapache:mainfrom
robreeves:fix-deepcopy-apache

Conversation

@robreeves
Copy link
Copy Markdown

@robreeves robreeves commented Apr 28, 2026

Closes #3297

Rationale for this change

copy.deepcopy() on And, Or, and Not expressions raises TypeError because Pydantic v2's default __deepcopy__ calls cls.__new__(cls) with no args, but these classes require positional arguments in __new__.

The fix adds __deepcopy__ to And, Or, and Not that deepcopy their fields and call the constructor directly.

Are these changes tested?

Yes. 11 new unit tests covering all expression types, balanced trees, nested expressions, and deepcopy followed by pickle.

Are there any user-facing changes?

Yes, copy.deepcopy() on expressions now works instead of raising an exception.

Pydantic v2's BaseModel.__deepcopy__ calls cls.__new__(cls) with no
args, but And, Or, and Not define __new__ with required positional
arguments. These tests reproduce the TypeError on deepcopy.
Add __deepcopy__ to BooleanExpression that reconstructs the expression
via model_fields, and returns self for Singleton subclasses. Fixes
TypeError from Pydantic v2's BaseModel.__deepcopy__ calling
cls.__new__(cls) with no args on And, Or, and Not which require
positional arguments in __new__.
Instead of a generic __deepcopy__ on BooleanExpression with Pydantic
internals, add simple __deepcopy__ methods to the three classes that
need them. Also add identity assertions for non-Singleton copies.
Comment thread tests/expressions/test_expressions.py Outdated
Copy link
Copy Markdown
Contributor

@rambleraptor rambleraptor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems pretty straight forward. Thanks for doing this!

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.

copy.deepcopy() raises TypeError on And, Or, Not expressions

3 participants