Implementation:Anthropics Anthropic sdk python General Utils
| Knowledge Sources | |
|---|---|
| Domains | SDK_Infrastructure, Utility_Functions |
| Last Updated | 2026-02-15 12:00 GMT |
Overview
General-purpose utility functions providing type guards, data manipulation, string helpers, runtime argument validation, and value coercion used throughout the Anthropic Python SDK.
Description
The _utils.py module is the largest utility module in the SDK, serving as the foundational helper layer that nearly every other module depends on. It contains type-safe guard functions (is_dict, is_list, is_mapping, is_given, etc.) for narrowing types in conditional checks, which are essential for maintaining type safety across the codebase without triggering Pyright errors from standard isinstance narrowing.
The module also provides the extract_files function for recursively pulling file content from nested dictionaries based on path specifications, the required_args decorator for enforcing overloaded function argument constraints at runtime, strip_not_given for removing NotGiven sentinel values from request payloads, and deepcopy_minimal for performance-optimized dict/list cloning. String helpers include removeprefix/removesuffix backports for Python < 3.9, human_join for natural-language list joining, and quote for wrapping strings in single quotes.
Additional utilities include value coercion functions (coerce_integer, coerce_float, coerce_boolean and their maybe_* nullable variants), get_required_header for case-insensitive header extraction, get_async_library for detecting the current async runtime via sniffio, a typed lru_cache wrapper, and json_safe for recursively converting data structures to JSON-serializable form.
Usage
These utilities are used internally throughout the SDK. is_given is used in virtually every resource method to check whether optional parameters were provided. required_args decorates the actual implementations of overloaded methods like create(). strip_not_given is used to clean request headers. extract_files is used when preparing multipart file uploads.
Code Reference
Source Location
- Repository: Anthropic SDK Python
- File:
src/anthropic/_utils/_utils.py(421 lines)
Key Signatures
def flatten(t: Iterable[Iterable[_T]]) -> list[_T]
def extract_files(
query: Mapping[str, object],
*,
paths: Sequence[Sequence[str]],
) -> list[tuple[str, FileTypes]]
def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]
def is_dict(obj: object) -> TypeGuard[dict[object, object]]
def is_list(obj: object) -> TypeGuard[list[object]]
def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]
def is_sequence(obj: object) -> TypeGuard[Sequence[object]]
def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]
def is_iterable(obj: object) -> TypeGuard[Iterable[object]]
def deepcopy_minimal(item: _T) -> _T
def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str
def quote(string: str) -> str
def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]
def strip_not_given(obj: object | None) -> object
def coerce_integer(val: str) -> int
def coerce_float(val: str) -> float
def coerce_boolean(val: str) -> bool
def maybe_coerce_integer(val: str | None) -> int | None
def maybe_coerce_float(val: str | None) -> float | None
def maybe_coerce_boolean(val: str | None) -> bool | None
def removeprefix(string: str, prefix: str) -> str
def removesuffix(string: str, suffix: str) -> str
def file_from_path(path: str) -> FileTypes
def get_required_header(headers: HeadersLike, header: str) -> str
def get_async_library() -> str
def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]
def json_safe(data: object) -> object
Import
from anthropic._utils._utils import (
flatten,
extract_files,
is_given,
is_dict,
is_list,
required_args,
strip_not_given,
deepcopy_minimal,
human_join,
json_safe,
)
I/O Contract
Type Guard Functions
| Function | Input | Output | Purpose |
|---|---|---|---|
is_given |
NotGiven | Omit | TypeGuard[_T] |
Checks if a value was explicitly provided (not a sentinel) |
is_dict |
object |
TypeGuard[dict[object, object]] |
Type-safe dict check |
is_list |
object |
TypeGuard[list[object]] |
Type-safe list check |
is_mapping |
object |
TypeGuard[Mapping[str, object]] |
Type-safe mapping check |
is_tuple |
object |
TypeGuard[tuple[object, ...]] |
Type-safe tuple check |
is_sequence |
object |
TypeGuard[Sequence[object]] |
Type-safe sequence check |
is_iterable |
object |
TypeGuard[Iterable[object]] |
Type-safe iterable check |
Data Manipulation Functions
| Function | Input | Output | Purpose |
|---|---|---|---|
extract_files |
Mapping[str, object], paths: Sequence[Sequence[str]] |
list[tuple[str, FileTypes]] |
Recursively extracts file content from nested dicts; mutates input |
strip_not_given |
None | object |
Removes top-level keys with NotGiven values from a mapping
|
deepcopy_minimal |
_T |
_T |
Fast deep copy limited to dicts and lists only |
json_safe |
object |
object |
Recursively converts mappings, sequences, and dates to JSON-serializable form |
required_args Decorator
| Input | Output | Behavior |
|---|---|---|
*variants: Sequence[str] -- one or more lists of required parameter names |
Callable[[CallableT], CallableT] |
Enforces at runtime that at least one variant set of arguments was passed; raises TypeError with a descriptive message if none match
|
Usage Examples
from anthropic._utils._utils import is_given, strip_not_given, human_join
from anthropic._types import NotGiven, not_given
# Check if an optional parameter was provided
value = not_given
if is_given(value):
print("Value was provided")
else:
print("Value was not provided") # This prints
# Strip NotGiven values from a dict before sending to API
params = {"model": "claude-sonnet-4-20250514", "temperature": not_given, "top_k": 5}
cleaned = strip_not_given(params)
# Result: {"model": "claude-sonnet-4-20250514", "top_k": 5}
# Human-readable list joining
human_join(["a", "b", "c"]) # "a, b or c"
human_join(["a", "b"], final="and") # "a and b"
human_join(["a"]) # "a"
# Using required_args decorator for overloaded functions
from anthropic._utils._utils import required_args
@required_args(["a"], ["b"])
def my_func(*, a: str | None = None, b: bool | None = None) -> str:
return a or str(b)
Dependencies
- sniffio -- Async library detection in
get_async_library() - functools -- Underlying
lru_cacheandwraps - inspect -- Function signature introspection for
required_args - pathlib -- File reading in
file_from_path