clientx 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clientx/_registry.py ADDED
@@ -0,0 +1,32 @@
1
+ """Map endpoint functions to their ``Endpoint`` objects.
2
+
3
+ The verb decorators register each endpoint function here, so ``_class_setup.py``
4
+ can find a client's or resource's endpoints when the class is defined, to check
5
+ them and apply a resource's prefix and tags. ``Endpoint`` is imported only for
6
+ type checking: nothing here uses it at runtime.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ if TYPE_CHECKING:
15
+ from clientx._endpoint import Endpoint
16
+
17
+ # Keyed by id() so lookups never hash arbitrary class attributes. Each entry
18
+ # keeps its function alive, so the id can't be reused by another object.
19
+ _endpoints: dict[int, tuple[Callable[..., Any], Endpoint]] = {}
20
+
21
+
22
+ def register_endpoint_function(func: Callable[..., Any], endpoint: Endpoint) -> None:
23
+ """Record that the decorator returned ``func`` for ``endpoint``."""
24
+ _endpoints[id(func)] = (func, endpoint)
25
+
26
+
27
+ def endpoint_for(value: object) -> Endpoint | None:
28
+ """Return the ``Endpoint`` of an endpoint function, or ``None``."""
29
+ entry = _endpoints.get(id(value))
30
+ if entry is not None and entry[0] is value:
31
+ return entry[1]
32
+ return None
clientx/_signature.py ADDED
@@ -0,0 +1,312 @@
1
+ """Inspect a callable's signature once, into data the rest of ClientX reads.
2
+
3
+ The decorator in ``_method.py`` calls ``inspect_signature`` on each endpoint
4
+ method when the class body runs. The result records each parameter's resolved
5
+ annotation, its type without ``Annotated``, and the request part a
6
+ ``clientx.arguments`` helper marks it for, so nothing reads annotations again at
7
+ call time.
8
+ """
9
+
10
+ import inspect
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, field
13
+ from typing import Annotated, Any, TypeAliasType, get_args, get_origin, get_type_hints
14
+
15
+ from pydantic.fields import FieldInfo
16
+
17
+ from clientx._arguments import get_httpx_argument
18
+ from clientx._types import HttpxArgument, Send
19
+
20
+ ParameterKind = inspect._ParameterKind # pyright: ignore[reportPrivateUsage]
21
+ """A parameter's kind, such as positional-only or keyword-only.
22
+
23
+ ``inspect`` has no public name for it.
24
+ """
25
+
26
+ NO_VALUE = inspect.Parameter.empty
27
+ """Marks a missing annotation or default, as ``inspect`` does.
28
+
29
+ It's the same object as ``inspect.Signature.empty``.
30
+ """
31
+
32
+
33
+ # --- What a signature holds ---------------------------------------------------
34
+ @dataclass(slots=True)
35
+ class ParameterInfo:
36
+ """One parameter of an inspected callable.
37
+
38
+ Only ``name``, ``position``, ``kind``, ``annotation`` and ``default`` are
39
+ passed in; ``__post_init__`` derives the rest from ``annotation``.
40
+
41
+ Attributes:
42
+ name: The parameter's name.
43
+ position: Its zero-based position in the signature.
44
+ kind: Positional-only, positional-or-keyword, ``*args``, keyword-only,
45
+ or ``**kwargs``.
46
+ base_type: ``annotation`` without its ``Annotated`` wrapper or ``type``
47
+ alias, or ``NO_VALUE`` if there's no annotation.
48
+ httpx_argument: The request part the parameter's helper marks it for.
49
+ ``None`` without a helper, which only a path placeholder's parameter
50
+ may lack.
51
+ clientx_field_info: The ``FieldInfo`` of the parameter's
52
+ ``clientx.arguments`` helper, such as ``Query()``, from the
53
+ ``Annotated`` metadata; ``None`` without one. If there are several
54
+ helpers, the last one wins. A plain ``Field(gt=0)`` isn't a helper,
55
+ so it's skipped. A helper nested inside another type, such as
56
+ ``Annotated[int, Query()] | None``, isn't found. Only the annotation
57
+ is read, by design: a helper given as the default value isn't found,
58
+ so there's no annotation and default to reconcile.
59
+ send: The last ``Send`` in the outermost ``Annotated``, so one on the
60
+ parameter wins over one from a ``type`` alias; ``Send()`` without
61
+ one.
62
+ annotation: The resolved annotation, with ``Annotated`` kept, or
63
+ ``NO_VALUE`` if there's none.
64
+ default: The default value, or ``NO_VALUE`` if there's none.
65
+ """
66
+
67
+ name: str
68
+ position: int
69
+ kind: ParameterKind
70
+ base_type: Any = field(init=False)
71
+ httpx_argument: HttpxArgument | None = field(default=None, init=False)
72
+ clientx_field_info: FieldInfo | None = field(default=None, init=False)
73
+ send: Send = field(default_factory=Send, init=False)
74
+ annotation: Any = NO_VALUE
75
+ default: Any = NO_VALUE
76
+
77
+ def __post_init__(self) -> None:
78
+ """Set ``base_type``, the helper's attributes and ``send``."""
79
+ base_type, metadata = unwrap_annotated(self.annotation)
80
+ self.base_type = base_type
81
+ self._read_metadata(metadata)
82
+
83
+ def _read_metadata(self, metadata: tuple[Any, ...]) -> None:
84
+ """Set the helper's attributes and ``send`` from ``metadata``.
85
+
86
+ Both come from the end of ``metadata``. The helper is the last
87
+ ``FieldInfo`` that a ``clientx.arguments`` helper marked, so in
88
+ ``Annotated[int, Query(), Header()]``, ``Header()`` wins; a plain
89
+ ``FieldInfo``, such as ``Field(gt=0)``, is skipped. ``send`` is the last
90
+ ``Send``, whole. Without a helper, ``clientx_field_info`` and
91
+ ``httpx_argument`` stay ``None``; without a ``Send``, ``send`` stays
92
+ ``Send()``.
93
+
94
+ Args:
95
+ metadata: The ``Annotated`` metadata, in the order
96
+ ``unwrap_annotated`` returns it: inner first, so a helper or
97
+ ``Send`` on the parameter wins over one from a ``type`` alias.
98
+ """
99
+ found_send = False
100
+ for meta in reversed(metadata):
101
+ if self.clientx_field_info is None and isinstance(meta, FieldInfo):
102
+ if (httpx_argument := get_httpx_argument(meta)) is not None:
103
+ self.httpx_argument = httpx_argument
104
+ self.clientx_field_info = meta
105
+ if not found_send and isinstance(meta, Send):
106
+ self.send = meta
107
+ found_send = True
108
+
109
+ if self.clientx_field_info is not None and found_send:
110
+ break
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class ReturnInfo:
115
+ """The return annotation of an inspected callable.
116
+
117
+ Attributes:
118
+ annotation: The resolved return annotation, with ``Annotated`` kept, or
119
+ ``NO_VALUE`` if there's none. ``-> None`` comes back as
120
+ ``type(None)``, as ``typing.get_type_hints`` returns it.
121
+ base_type: ``annotation`` without its ``Annotated`` wrapper or ``type``
122
+ alias.
123
+ metadata: The ``Annotated`` metadata, or ``()``.
124
+ """
125
+
126
+ annotation: Any
127
+ base_type: Any
128
+ metadata: tuple[Any, ...]
129
+
130
+
131
+ @dataclass(frozen=True, slots=True)
132
+ class BoundCall:
133
+ """A call's arguments, bound to a signature, with defaults filled in.
134
+
135
+ Attributes:
136
+ arguments: Each parameter's value by name, in signature order. A
137
+ ``*args`` parameter gets a tuple and a ``**kwargs`` parameter a
138
+ dict, empty when the call passes none.
139
+ passed: The names of the parameters the caller passed a value for, so
140
+ a ``None`` passed explicitly can be told from a default ``None``.
141
+ """
142
+
143
+ arguments: dict[str, Any]
144
+ passed: frozenset[str]
145
+
146
+
147
+ @dataclass(frozen=True)
148
+ class SignatureInfo:
149
+ """What ClientX needs from a callable's signature, read once.
150
+
151
+ Attributes:
152
+ func: The inspected callable, as given.
153
+ name: Its ``__name__``, or its ``repr`` if it has none.
154
+ qualname: Its ``__qualname__``, or its ``repr`` if it has none.
155
+ module: Its ``__module__``, or ``None``.
156
+ doc: Its docstring, cleaned up by ``inspect.getdoc``, or ``None``.
157
+ is_async: Whether it's an ``async def`` function, after following
158
+ ``__wrapped__``.
159
+ parameters: One ``ParameterInfo`` per parameter, in order.
160
+ returns: The return annotation.
161
+ signature: The signature from ``inspect.signature``, with annotations as
162
+ written (not resolved). ``bind`` uses it.
163
+ """
164
+
165
+ func: Callable[..., Any]
166
+ name: str
167
+ qualname: str
168
+ module: str | None
169
+ doc: str | None
170
+ is_async: bool
171
+ parameters: tuple[ParameterInfo, ...]
172
+ returns: ReturnInfo
173
+ signature: inspect.Signature = field(repr=False)
174
+
175
+ def bind(self, *args: Any, **kwargs: Any) -> BoundCall:
176
+ """Bind a call's arguments to the signature, with defaults filled in.
177
+
178
+ Raises:
179
+ TypeError: If the arguments don't fit the signature, as in a normal
180
+ call.
181
+ """
182
+ bound = self.signature.bind(*args, **kwargs)
183
+ # Read before apply_defaults, which adds the parameters not passed.
184
+ passed = frozenset(bound.arguments)
185
+ bound.apply_defaults()
186
+ return BoundCall(bound.arguments, passed)
187
+
188
+
189
+ # --- Annotations --------------------------------------------------------------
190
+ # Enough for any real chain of aliases, and a stop for cyclic ones such as
191
+ # `type A = B` with `type B = A`.
192
+ _MAX_ALIAS_DEPTH = 100
193
+
194
+
195
+ def unwrap_annotated(type_hint: Any) -> tuple[Any, tuple[Any, ...]]:
196
+ """Split an ``Annotated`` type hint into its type and its metadata.
197
+
198
+ A ``type`` alias is expanded, whether it's the whole hint or the type inside
199
+ an ``Annotated``, so ``Annotated`` metadata inside one is found too. Nested
200
+ ``Annotated`` hints are flattened into one tuple, inner metadata first, the
201
+ order Python uses when it flattens them itself. A hint that isn't
202
+ ``Annotated`` comes back with empty metadata::
203
+
204
+ unwrap_annotated(Annotated[int, Range(1, 10), Doc("id")])
205
+ -> (int, (Range(1, 10), Doc("id")))
206
+ unwrap_annotated(UserId) # type UserId = Annotated[int, Doc("id")]
207
+ -> (int, (Doc("id"),))
208
+ unwrap_annotated(str)
209
+ -> (str, ())
210
+ """
211
+ collected_metadata: tuple[Any, ...] = ()
212
+ type_hint = _unwrap_type_alias(type_hint)
213
+ while get_origin(type_hint) is Annotated:
214
+ underlying_type, *metadata_items = get_args(type_hint)
215
+ # Prepend: metadata from an alias inside comes before this level's, as
216
+ # in a nested Annotated.
217
+ collected_metadata = (*metadata_items, *collected_metadata)
218
+ type_hint = _unwrap_type_alias(underlying_type)
219
+ return type_hint, collected_metadata
220
+
221
+
222
+ def _unwrap_type_alias(annotation: Any) -> Any:
223
+ """Replace a PEP 695 ``type`` alias with the type it stands for.
224
+
225
+ ``type UserId = Annotated[int, ...]`` becomes ``Annotated[int, ...]``, and
226
+ ``QueryT[int]`` for ``type QueryT[T] = Annotated[T, ...]`` becomes
227
+ ``Annotated[int, ...]``. Python expands plain assignment aliases itself, but
228
+ not these, so their ``Annotated`` metadata would otherwise be lost.
229
+ """
230
+ for _ in range(_MAX_ALIAS_DEPTH):
231
+ if isinstance(annotation, TypeAliasType):
232
+ annotation = annotation.__value__
233
+ elif isinstance(alias := get_origin(annotation), TypeAliasType):
234
+ try:
235
+ annotation = alias.__value__[get_args(annotation)]
236
+ except TypeError:
237
+ # The alias's value can't take the arguments (for example
238
+ # `type X[T] = int`).
239
+ annotation = alias.__value__
240
+ else:
241
+ break
242
+ return annotation
243
+
244
+
245
+ def _resolve_type_hints(func: Callable[..., Any]) -> dict[str, Any]:
246
+ """Return the callable's type hints, evaluated, with ``Annotated`` kept.
247
+
248
+ It reads the hints of the function ``func`` wraps, following
249
+ ``__wrapped__``. ``include_extras=True`` keeps the ``Annotated`` wrappers
250
+ that ``typing.get_type_hints`` would otherwise strip.
251
+
252
+ Raises:
253
+ NameError: If an annotation names something that isn't defined yet. For
254
+ an endpoint that's checked when its class body runs, so a model
255
+ defined further down the module isn't found. Other errors from
256
+ ``typing.get_type_hints`` propagate too.
257
+ """
258
+ return get_type_hints(inspect.unwrap(func), include_extras=True)
259
+
260
+
261
+ # --- Entry point --------------------------------------------------------------
262
+ def inspect_signature(func: Callable[..., Any]) -> SignatureInfo:
263
+ """Inspect a callable once and return what ClientX needs from its signature.
264
+
265
+ Every parameter is described as written, including a ``self`` parameter:
266
+ what a parameter means, such as the first one of an endpoint, is up to the
267
+ caller.
268
+
269
+ Args:
270
+ func: The callable to inspect. A ``functools.wraps`` wrapper is read
271
+ through to the function it wraps.
272
+
273
+ Returns:
274
+ The callable's ``SignatureInfo``.
275
+
276
+ Raises:
277
+ NameError: If an annotation names something that isn't defined yet.
278
+ ValueError: If ``inspect.signature`` can't find a signature, as for some
279
+ builtins.
280
+ TypeError: If ``func`` is an object ``inspect.signature`` doesn't
281
+ support.
282
+ """
283
+ signature = inspect.signature(func)
284
+ resolved_type_hints = _resolve_type_hints(func)
285
+
286
+ parameters: list[ParameterInfo] = [
287
+ ParameterInfo(
288
+ name=raw_parameter.name,
289
+ position=position,
290
+ kind=raw_parameter.kind,
291
+ annotation=resolved_type_hints.get(raw_parameter.name, raw_parameter.annotation),
292
+ default=raw_parameter.default,
293
+ )
294
+ for position, raw_parameter in enumerate(signature.parameters.values())
295
+ ]
296
+
297
+ return_annotation = resolved_type_hints.get("return", signature.return_annotation)
298
+ return_base_type, return_metadata = unwrap_annotated(return_annotation)
299
+
300
+ original_function = inspect.unwrap(func)
301
+
302
+ return SignatureInfo(
303
+ func=func,
304
+ name=getattr(func, "__name__", repr(func)),
305
+ qualname=getattr(func, "__qualname__", repr(func)),
306
+ module=getattr(func, "__module__", None),
307
+ doc=inspect.getdoc(func),
308
+ is_async=inspect.iscoroutinefunction(original_function),
309
+ parameters=tuple(parameters),
310
+ returns=ReturnInfo(return_annotation, return_base_type, return_metadata),
311
+ signature=signature,
312
+ )