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
45 changes: 41 additions & 4 deletions tests/test_deepcopy.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,44 @@ def test_ignores_other_types() -> None:
assert_different_identities(obj1, obj2)
assert obj1["foo"] is my_obj

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

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


def test_tuple_with_mutable_contents() -> None:
"""Tuples containing mutable objects (like FileTypes headers) must be deep copied."""
headers = {"X-Custom": "value"}
obj1 = ("test.txt", b"hello", "text/plain", headers)
obj2 = deepcopy_minimal(obj1)
assert_different_identities(obj1, obj2)
assert_different_identities(obj1[3], obj2[3])
# Mutating the copy must not affect the original
obj2[3]["X-Injected"] = "surprise"
assert "X-Injected" not in headers


def test_dict_containing_tuple() -> None:
"""Simulates the files.beta.upload body: deepcopy_minimal({'file': file_tuple})."""
headers = {"Authorization": "Bearer xyz"}
file_tuple = ("doc.pdf", b"data", "application/pdf", headers)
body = {"file": file_tuple}
body_copy = deepcopy_minimal(body)
assert_different_identities(body, body_copy)
assert_different_identities(body["file"], body_copy["file"])
assert_different_identities(body["file"][3], body_copy["file"][3])
# Mutating the copy's headers must not affect the original
body_copy["file"][3]["X-Mutated"] = "yes"
assert "X-Mutated" not in headers


def test_list_of_tuples() -> None:
"""Simulates the skills/versions.py body: deepcopy_minimal({'files': [file_tuple, ...]})."""
headers = {"X-H": "v"}
files = [("a.txt", b"data", "text/plain", headers)]
body = {"files": files}
body_copy = deepcopy_minimal(body)
assert_different_identities(body_copy["files"][0], body["files"][0])
assert_different_identities(body_copy["files"][0][3], body["files"][0][3])