Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch Exceptions in smart_deepcopy #4187

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/4184-coneybeare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Catch certain raised errors in `smart_deepcopy` and revert to `deepcopy` if so.
11 changes: 8 additions & 3 deletions pydantic/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,9 +651,14 @@ def smart_deepcopy(obj: Obj) -> Obj:
obj_type = obj.__class__
if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES:
return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway
elif not obj and obj_type in BUILTIN_COLLECTIONS:
# faster way for empty collections, no need to copy its members
return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method
try:
if not obj and obj_type in BUILTIN_COLLECTIONS:
# faster way for empty collections, no need to copy its members
return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method
except (TypeError, ValueError, RuntimeError):
# do we really dare to catch ALL errors? Seems a bit risky
coneybeare marked this conversation as resolved.
Show resolved Hide resolved
pass

return deepcopy(obj) # slowest way when we actually might need a deepcopy


Expand Down
11 changes: 11 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,17 @@ def test_smart_deepcopy_collection(collection, mocker):
assert smart_deepcopy(collection) is expected_value


@pytest.mark.parametrize('error', [TypeError, ValueError, RuntimeError])
def test_smart_deepcopy_error(error, mocker):
class RaiseOnBooleanOperation(str):
def __bool__(self):
raise error('raised error')

obj = RaiseOnBooleanOperation()
expected_value = deepcopy(obj)
assert smart_deepcopy(obj) == expected_value


T = TypeVar('T')


Expand Down