Skip to content

fix: handle tuples in deepcopy_minimal to prevent dict mutation#1245

Open
passionworkeer wants to merge 2 commits intoanthropics:mainfrom
passionworkeer:fix/deepcopy-minimal-tuple
Open

fix: handle tuples in deepcopy_minimal to prevent dict mutation#1245
passionworkeer wants to merge 2 commits intoanthropics:mainfrom
passionworkeer:fix/deepcopy-minimal-tuple

Conversation

@passionworkeer
Copy link

Summary

Fixes an issue where deepcopy_minimal was mutating dicts nested inside tuples.

Problem

The deepcopy_minimal function in _utils.py only handled dict and list types. When a tuple containing a dict was passed to functions like iles.beta.upload, the dict inside the tuple could be mutated in-place during processing.

Solution

Added tuple handling to deepcopy_minimal:

python if isinstance(item, tuple): return cast(_T, tuple(deepcopy_minimal(entry) for entry in item))

This ensures that any dicts or lists nested inside tuples are properly deep-copied, preventing in-place mutations.

Changes

  • Added tuple handling to deepcopy_minimal function in src/anthropic/_utils/_utils.py
  • Updated docstring to document tuple support

Closes #1202

The deepcopy_minimal function only handled dict and list types, but not
tuples. When a tuple containing a dict was passed, the dict inside the
tuple could be mutated in-place during processing.

This fix adds tuple handling to recursively copy tuple elements, preventing
in-place mutations of dicts or lists nested inside tuples.

Closes anthropics#1202
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes deepcopy_minimal so it also deep-copies tuples (recursively), preventing in-place mutation of dicts/lists nested inside tuples (e.g., in files.beta.upload file tuples).

Changes:

  • Documented tuple support in deepcopy_minimal’s docstring.
  • Added recursive tuple handling to deepcopy_minimal.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +192 to +193
if isinstance(item, tuple):
return cast(_T, tuple(deepcopy_minimal(entry) for entry in item))
return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()})
if is_list(item):
return cast(_T, [deepcopy_minimal(entry) for entry in item])
if isinstance(item, tuple):
- Use is_tuple() TypeGuard helper instead of isinstance check
- Update test_ignores_other_types to reflect new tuple behavior
- Add assertion that dict nested inside tuple is copied
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.

Use of deepcopy_minimal in files.beta.upload mutates dict in place

2 participants