Debian Codegraph @

src/anthropic/_utils/_reflection.py

raw
1 from __future__ import annotations
2
3 import sys
4 import inspect
5 import typing_extensions
6 from typing import Any, Callable
7
8
9 def signature_without_evaluating_annotations(func: Callable[..., Any]) -> inspect.Signature:
10 """Like `inspect.signature()`, for callers that only need parameter names, kinds and defaults.
11
12 Python 3.14 evaluates annotations lazily and `inspect.signature()` evaluates them by default, so a
13 function annotated with a name that only exists under `TYPE_CHECKING` makes it raise `NameError`.
14 Here the annotations come back as strings on 3.14+ and are never evaluated. On older versions
15 they are whatever the function already holds.
16 """
17 if sys.version_info >= (3, 14):
18 import annotationlib
19
20 return inspect.signature(func, annotation_format=annotationlib.Format.STRING)
21 return inspect.signature(func)
22
23
24 def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool:
25 """Returns whether or not the given function has a specific parameter"""
26 sig = signature_without_evaluating_annotations(func)
27 return arg_name in sig.parameters
28
29
30 def assert_signatures_in_sync(
31 source_func: Callable[..., Any],
32 check_func: Callable[..., Any],
33 *,
34 exclude_params: set[str] = set(),
35 ) -> None:
36 """Ensure that the signature of the second function matches the first."""
37
38 check_sig = inspect.signature(check_func)
39 source_sig = inspect.signature(source_func)
40
41 errors: list[str] = []
42
43 for name, source_param in source_sig.parameters.items():
44 if name in exclude_params:
45 continue
46
47 custom_param = check_sig.parameters.get(name)
48 if not custom_param:
49 errors.append(f"the `{name}` param is missing")
50 continue
51
52 if custom_param.annotation != source_param.annotation:
53 errors.append(
54 f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}"
55 )
56 continue
57
58 if errors:
59 raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors))
60
61
62 def assert_overloads_in_sync(
63 source_func: Callable[..., Any],
64 overloaded_func: Callable[..., Any],
65 *,
66 exclude_params: set[str] = set(),
67 ) -> None:
68 """Ensure that every @overload of overloaded_func contains all params from source_func."""
69 source_sig = inspect.signature(source_func)
70 overloads = typing_extensions.get_overloads(overloaded_func)
71
72 if not overloads:
73 raise AssertionError(f"No @overload definitions found for {overloaded_func!r}")
74
75 errors: list[str] = []
76
77 for i, overload_fn in enumerate(overloads):
78 overload_sig = inspect.signature(overload_fn)
79 for name, source_param in source_sig.parameters.items():
80 if name in exclude_params:
81 continue
82
83 overload_param = overload_sig.parameters.get(name)
84 if not overload_param:
85 errors.append(f"overload {i}: `{name}` param is missing")
86 continue
87
88 if overload_param.annotation != source_param.annotation:
89 errors.append(
90 f"overload {i}: types for `{name}` do not match; source={repr(source_param.annotation)} overload={repr(overload_param.annotation)}"
91 )
92
93 if errors:
94 raise AssertionError(
95 f"{len(errors)} errors encountered when comparing overload signatures:\n\n" + "\n\n".join(errors)
96 )