Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/anthropic/_utils/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,13 +181,16 @@ def deepcopy_minimal(item: _T) -> _T:

- mappings, e.g. `dict`
- list
- tuple

This is done for performance reasons.
"""
if is_mapping(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 is_tuple(item):
return cast(_T, tuple(deepcopy_minimal(entry) for entry in item))
return item


Expand Down
36 changes: 31 additions & 5 deletions tests/test_deepcopy.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,37 @@ def test_nested_list() -> None:
assert_different_identities(obj1[1], obj2[1])


def test_simple_tuple() -> None:
obj1 = ("a", "b", "c")
obj2 = deepcopy_minimal(obj1)
assert_different_identities(obj1, obj2)


def test_tuple_with_nested_dict() -> None:
"""Tuples containing dicts should have those dicts deep-copied.

This is the core fix for issue #1202: FileTypes tuples like
(filename, content, content_type, headers_dict) must not share
the headers dict reference with the original.
"""
headers = {"X-Custom": "value"}
obj1 = ("file.txt", b"content", "text/plain", headers)
obj2 = deepcopy_minimal(obj1)
assert_different_identities(obj1, obj2)
# The nested dict inside the tuple must be a separate copy
assert_different_identities(obj1[3], obj2[3])


def test_dict_with_tuple_value() -> None:
"""Dicts containing tuples with nested dicts should be fully deep-copied."""
inner_dict = {"key": "value"}
obj1 = {"file": ("name", b"data", "type", inner_dict)}
obj2 = deepcopy_minimal(obj1)
assert_different_identities(obj1, obj2)
assert_different_identities(obj1["file"], obj2["file"])
assert_different_identities(obj1["file"][3], obj2["file"][3])


class MyObject: ...


Expand All @@ -51,8 +82,3 @@ def test_ignores_other_types() -> None:
obj2 = deepcopy_minimal(obj1)
assert_different_identities(obj1, obj2)
assert obj1["foo"] is my_obj

# tuples
obj3 = ("a", "b")
obj4 = deepcopy_minimal(obj3)
assert obj3 is obj4