isaacus 0.1.0a1__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.
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from typing import Any, Callable
5
+
6
+
7
+ def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool:
8
+ """Returns whether or not the given function has a specific parameter"""
9
+ sig = inspect.signature(func)
10
+ return arg_name in sig.parameters
11
+
12
+
13
+ def assert_signatures_in_sync(
14
+ source_func: Callable[..., Any],
15
+ check_func: Callable[..., Any],
16
+ *,
17
+ exclude_params: set[str] = set(),
18
+ ) -> None:
19
+ """Ensure that the signature of the second function matches the first."""
20
+
21
+ check_sig = inspect.signature(check_func)
22
+ source_sig = inspect.signature(source_func)
23
+
24
+ errors: list[str] = []
25
+
26
+ for name, source_param in source_sig.parameters.items():
27
+ if name in exclude_params:
28
+ continue
29
+
30
+ custom_param = check_sig.parameters.get(name)
31
+ if not custom_param:
32
+ errors.append(f"the `{name}` param is missing")
33
+ continue
34
+
35
+ if custom_param.annotation != source_param.annotation:
36
+ errors.append(
37
+ f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}"
38
+ )
39
+ continue
40
+
41
+ if errors:
42
+ raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors))
@@ -0,0 +1,12 @@
1
+ from typing import Any
2
+ from typing_extensions import Iterator, AsyncIterator
3
+
4
+
5
+ def consume_sync_iterator(iterator: Iterator[Any]) -> None:
6
+ for _ in iterator:
7
+ ...
8
+
9
+
10
+ async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None:
11
+ async for _ in iterator:
12
+ ...
@@ -0,0 +1,86 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import asyncio
5
+ import functools
6
+ import contextvars
7
+ from typing import Any, TypeVar, Callable, Awaitable
8
+ from typing_extensions import ParamSpec
9
+
10
+ import anyio
11
+ import sniffio
12
+ import anyio.to_thread
13
+
14
+ T_Retval = TypeVar("T_Retval")
15
+ T_ParamSpec = ParamSpec("T_ParamSpec")
16
+
17
+
18
+ if sys.version_info >= (3, 9):
19
+ _asyncio_to_thread = asyncio.to_thread
20
+ else:
21
+ # backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
22
+ # for Python 3.8 support
23
+ async def _asyncio_to_thread(
24
+ func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
25
+ ) -> Any:
26
+ """Asynchronously run function *func* in a separate thread.
27
+
28
+ Any *args and **kwargs supplied for this function are directly passed
29
+ to *func*. Also, the current :class:`contextvars.Context` is propagated,
30
+ allowing context variables from the main thread to be accessed in the
31
+ separate thread.
32
+
33
+ Returns a coroutine that can be awaited to get the eventual result of *func*.
34
+ """
35
+ loop = asyncio.events.get_running_loop()
36
+ ctx = contextvars.copy_context()
37
+ func_call = functools.partial(ctx.run, func, *args, **kwargs)
38
+ return await loop.run_in_executor(None, func_call)
39
+
40
+
41
+ async def to_thread(
42
+ func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
43
+ ) -> T_Retval:
44
+ if sniffio.current_async_library() == "asyncio":
45
+ return await _asyncio_to_thread(func, *args, **kwargs)
46
+
47
+ return await anyio.to_thread.run_sync(
48
+ functools.partial(func, *args, **kwargs),
49
+ )
50
+
51
+
52
+ # inspired by `asyncer`, https://github.com/tiangolo/asyncer
53
+ def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]:
54
+ """
55
+ Take a blocking function and create an async one that receives the same
56
+ positional and keyword arguments. For python version 3.9 and above, it uses
57
+ asyncio.to_thread to run the function in a separate thread. For python version
58
+ 3.8, it uses locally defined copy of the asyncio.to_thread function which was
59
+ introduced in python 3.9.
60
+
61
+ Usage:
62
+
63
+ ```python
64
+ def blocking_func(arg1, arg2, kwarg1=None):
65
+ # blocking code
66
+ return result
67
+
68
+
69
+ result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1)
70
+ ```
71
+
72
+ ## Arguments
73
+
74
+ `function`: a blocking regular callable (e.g. a function)
75
+
76
+ ## Return
77
+
78
+ An async function that takes the same positional and keyword arguments as the
79
+ original one, that when called runs the same original function in a thread worker
80
+ and returns the result.
81
+ """
82
+
83
+ async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval:
84
+ return await to_thread(function, *args, **kwargs)
85
+
86
+ return wrapper
@@ -0,0 +1,402 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import base64
5
+ import pathlib
6
+ from typing import Any, Mapping, TypeVar, cast
7
+ from datetime import date, datetime
8
+ from typing_extensions import Literal, get_args, override, get_type_hints
9
+
10
+ import anyio
11
+ import pydantic
12
+
13
+ from ._utils import (
14
+ is_list,
15
+ is_mapping,
16
+ is_iterable,
17
+ )
18
+ from .._files import is_base64_file_input
19
+ from ._typing import (
20
+ is_list_type,
21
+ is_union_type,
22
+ extract_type_arg,
23
+ is_iterable_type,
24
+ is_required_type,
25
+ is_annotated_type,
26
+ strip_annotated_type,
27
+ )
28
+ from .._compat import get_origin, model_dump, is_typeddict
29
+
30
+ _T = TypeVar("_T")
31
+
32
+
33
+ # TODO: support for drilling globals() and locals()
34
+ # TODO: ensure works correctly with forward references in all cases
35
+
36
+
37
+ PropertyFormat = Literal["iso8601", "base64", "custom"]
38
+
39
+
40
+ class PropertyInfo:
41
+ """Metadata class to be used in Annotated types to provide information about a given type.
42
+
43
+ For example:
44
+
45
+ class MyParams(TypedDict):
46
+ account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')]
47
+
48
+ This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API.
49
+ """
50
+
51
+ alias: str | None
52
+ format: PropertyFormat | None
53
+ format_template: str | None
54
+ discriminator: str | None
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ alias: str | None = None,
60
+ format: PropertyFormat | None = None,
61
+ format_template: str | None = None,
62
+ discriminator: str | None = None,
63
+ ) -> None:
64
+ self.alias = alias
65
+ self.format = format
66
+ self.format_template = format_template
67
+ self.discriminator = discriminator
68
+
69
+ @override
70
+ def __repr__(self) -> str:
71
+ return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')"
72
+
73
+
74
+ def maybe_transform(
75
+ data: object,
76
+ expected_type: object,
77
+ ) -> Any | None:
78
+ """Wrapper over `transform()` that allows `None` to be passed.
79
+
80
+ See `transform()` for more details.
81
+ """
82
+ if data is None:
83
+ return None
84
+ return transform(data, expected_type)
85
+
86
+
87
+ # Wrapper over _transform_recursive providing fake types
88
+ def transform(
89
+ data: _T,
90
+ expected_type: object,
91
+ ) -> _T:
92
+ """Transform dictionaries based off of type information from the given type, for example:
93
+
94
+ ```py
95
+ class Params(TypedDict, total=False):
96
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
97
+
98
+
99
+ transformed = transform({"card_id": "<my card ID>"}, Params)
100
+ # {'cardID': '<my card ID>'}
101
+ ```
102
+
103
+ Any keys / data that does not have type information given will be included as is.
104
+
105
+ It should be noted that the transformations that this function does are not represented in the type system.
106
+ """
107
+ transformed = _transform_recursive(data, annotation=cast(type, expected_type))
108
+ return cast(_T, transformed)
109
+
110
+
111
+ def _get_annotated_type(type_: type) -> type | None:
112
+ """If the given type is an `Annotated` type then it is returned, if not `None` is returned.
113
+
114
+ This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]`
115
+ """
116
+ if is_required_type(type_):
117
+ # Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]`
118
+ type_ = get_args(type_)[0]
119
+
120
+ if is_annotated_type(type_):
121
+ return type_
122
+
123
+ return None
124
+
125
+
126
+ def _maybe_transform_key(key: str, type_: type) -> str:
127
+ """Transform the given `data` based on the annotations provided in `type_`.
128
+
129
+ Note: this function only looks at `Annotated` types that contain `PropertInfo` metadata.
130
+ """
131
+ annotated_type = _get_annotated_type(type_)
132
+ if annotated_type is None:
133
+ # no `Annotated` definition for this type, no transformation needed
134
+ return key
135
+
136
+ # ignore the first argument as it is the actual type
137
+ annotations = get_args(annotated_type)[1:]
138
+ for annotation in annotations:
139
+ if isinstance(annotation, PropertyInfo) and annotation.alias is not None:
140
+ return annotation.alias
141
+
142
+ return key
143
+
144
+
145
+ def _transform_recursive(
146
+ data: object,
147
+ *,
148
+ annotation: type,
149
+ inner_type: type | None = None,
150
+ ) -> object:
151
+ """Transform the given data against the expected type.
152
+
153
+ Args:
154
+ annotation: The direct type annotation given to the particular piece of data.
155
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
156
+
157
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
158
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
159
+ the list can be transformed using the metadata from the container type.
160
+
161
+ Defaults to the same value as the `annotation` argument.
162
+ """
163
+ if inner_type is None:
164
+ inner_type = annotation
165
+
166
+ stripped_type = strip_annotated_type(inner_type)
167
+ origin = get_origin(stripped_type) or stripped_type
168
+ if is_typeddict(stripped_type) and is_mapping(data):
169
+ return _transform_typeddict(data, stripped_type)
170
+
171
+ if origin == dict and is_mapping(data):
172
+ items_type = get_args(stripped_type)[1]
173
+ return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
174
+
175
+ if (
176
+ # List[T]
177
+ (is_list_type(stripped_type) and is_list(data))
178
+ # Iterable[T]
179
+ or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
180
+ ):
181
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
182
+ # intended as an iterable, so we don't transform it.
183
+ if isinstance(data, dict):
184
+ return cast(object, data)
185
+
186
+ inner_type = extract_type_arg(stripped_type, 0)
187
+ return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
188
+
189
+ if is_union_type(stripped_type):
190
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
191
+ #
192
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
193
+ # in different subtypes.
194
+ for subtype in get_args(stripped_type):
195
+ data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
196
+ return data
197
+
198
+ if isinstance(data, pydantic.BaseModel):
199
+ return model_dump(data, exclude_unset=True, mode="json")
200
+
201
+ annotated_type = _get_annotated_type(annotation)
202
+ if annotated_type is None:
203
+ return data
204
+
205
+ # ignore the first argument as it is the actual type
206
+ annotations = get_args(annotated_type)[1:]
207
+ for annotation in annotations:
208
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
209
+ return _format_data(data, annotation.format, annotation.format_template)
210
+
211
+ return data
212
+
213
+
214
+ def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
215
+ if isinstance(data, (date, datetime)):
216
+ if format_ == "iso8601":
217
+ return data.isoformat()
218
+
219
+ if format_ == "custom" and format_template is not None:
220
+ return data.strftime(format_template)
221
+
222
+ if format_ == "base64" and is_base64_file_input(data):
223
+ binary: str | bytes | None = None
224
+
225
+ if isinstance(data, pathlib.Path):
226
+ binary = data.read_bytes()
227
+ elif isinstance(data, io.IOBase):
228
+ binary = data.read()
229
+
230
+ if isinstance(binary, str): # type: ignore[unreachable]
231
+ binary = binary.encode()
232
+
233
+ if not isinstance(binary, bytes):
234
+ raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
235
+
236
+ return base64.b64encode(binary).decode("ascii")
237
+
238
+ return data
239
+
240
+
241
+ def _transform_typeddict(
242
+ data: Mapping[str, object],
243
+ expected_type: type,
244
+ ) -> Mapping[str, object]:
245
+ result: dict[str, object] = {}
246
+ annotations = get_type_hints(expected_type, include_extras=True)
247
+ for key, value in data.items():
248
+ type_ = annotations.get(key)
249
+ if type_ is None:
250
+ # we do not have a type annotation for this field, leave it as is
251
+ result[key] = value
252
+ else:
253
+ result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_)
254
+ return result
255
+
256
+
257
+ async def async_maybe_transform(
258
+ data: object,
259
+ expected_type: object,
260
+ ) -> Any | None:
261
+ """Wrapper over `async_transform()` that allows `None` to be passed.
262
+
263
+ See `async_transform()` for more details.
264
+ """
265
+ if data is None:
266
+ return None
267
+ return await async_transform(data, expected_type)
268
+
269
+
270
+ async def async_transform(
271
+ data: _T,
272
+ expected_type: object,
273
+ ) -> _T:
274
+ """Transform dictionaries based off of type information from the given type, for example:
275
+
276
+ ```py
277
+ class Params(TypedDict, total=False):
278
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
279
+
280
+
281
+ transformed = transform({"card_id": "<my card ID>"}, Params)
282
+ # {'cardID': '<my card ID>'}
283
+ ```
284
+
285
+ Any keys / data that does not have type information given will be included as is.
286
+
287
+ It should be noted that the transformations that this function does are not represented in the type system.
288
+ """
289
+ transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type))
290
+ return cast(_T, transformed)
291
+
292
+
293
+ async def _async_transform_recursive(
294
+ data: object,
295
+ *,
296
+ annotation: type,
297
+ inner_type: type | None = None,
298
+ ) -> object:
299
+ """Transform the given data against the expected type.
300
+
301
+ Args:
302
+ annotation: The direct type annotation given to the particular piece of data.
303
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
304
+
305
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
306
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
307
+ the list can be transformed using the metadata from the container type.
308
+
309
+ Defaults to the same value as the `annotation` argument.
310
+ """
311
+ if inner_type is None:
312
+ inner_type = annotation
313
+
314
+ stripped_type = strip_annotated_type(inner_type)
315
+ origin = get_origin(stripped_type) or stripped_type
316
+ if is_typeddict(stripped_type) and is_mapping(data):
317
+ return await _async_transform_typeddict(data, stripped_type)
318
+
319
+ if origin == dict and is_mapping(data):
320
+ items_type = get_args(stripped_type)[1]
321
+ return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
322
+
323
+ if (
324
+ # List[T]
325
+ (is_list_type(stripped_type) and is_list(data))
326
+ # Iterable[T]
327
+ or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
328
+ ):
329
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
330
+ # intended as an iterable, so we don't transform it.
331
+ if isinstance(data, dict):
332
+ return cast(object, data)
333
+
334
+ inner_type = extract_type_arg(stripped_type, 0)
335
+ return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
336
+
337
+ if is_union_type(stripped_type):
338
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
339
+ #
340
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
341
+ # in different subtypes.
342
+ for subtype in get_args(stripped_type):
343
+ data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype)
344
+ return data
345
+
346
+ if isinstance(data, pydantic.BaseModel):
347
+ return model_dump(data, exclude_unset=True, mode="json")
348
+
349
+ annotated_type = _get_annotated_type(annotation)
350
+ if annotated_type is None:
351
+ return data
352
+
353
+ # ignore the first argument as it is the actual type
354
+ annotations = get_args(annotated_type)[1:]
355
+ for annotation in annotations:
356
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
357
+ return await _async_format_data(data, annotation.format, annotation.format_template)
358
+
359
+ return data
360
+
361
+
362
+ async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
363
+ if isinstance(data, (date, datetime)):
364
+ if format_ == "iso8601":
365
+ return data.isoformat()
366
+
367
+ if format_ == "custom" and format_template is not None:
368
+ return data.strftime(format_template)
369
+
370
+ if format_ == "base64" and is_base64_file_input(data):
371
+ binary: str | bytes | None = None
372
+
373
+ if isinstance(data, pathlib.Path):
374
+ binary = await anyio.Path(data).read_bytes()
375
+ elif isinstance(data, io.IOBase):
376
+ binary = data.read()
377
+
378
+ if isinstance(binary, str): # type: ignore[unreachable]
379
+ binary = binary.encode()
380
+
381
+ if not isinstance(binary, bytes):
382
+ raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
383
+
384
+ return base64.b64encode(binary).decode("ascii")
385
+
386
+ return data
387
+
388
+
389
+ async def _async_transform_typeddict(
390
+ data: Mapping[str, object],
391
+ expected_type: type,
392
+ ) -> Mapping[str, object]:
393
+ result: dict[str, object] = {}
394
+ annotations = get_type_hints(expected_type, include_extras=True)
395
+ for key, value in data.items():
396
+ type_ = annotations.get(key)
397
+ if type_ is None:
398
+ # we do not have a type annotation for this field, leave it as is
399
+ result[key] = value
400
+ else:
401
+ result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_)
402
+ return result
@@ -0,0 +1,149 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import typing
5
+ import typing_extensions
6
+ from typing import Any, TypeVar, Iterable, cast
7
+ from collections import abc as _c_abc
8
+ from typing_extensions import (
9
+ TypeIs,
10
+ Required,
11
+ Annotated,
12
+ get_args,
13
+ get_origin,
14
+ )
15
+
16
+ from .._types import InheritsGeneric
17
+ from .._compat import is_union as _is_union
18
+
19
+
20
+ def is_annotated_type(typ: type) -> bool:
21
+ return get_origin(typ) == Annotated
22
+
23
+
24
+ def is_list_type(typ: type) -> bool:
25
+ return (get_origin(typ) or typ) == list
26
+
27
+
28
+ def is_iterable_type(typ: type) -> bool:
29
+ """If the given type is `typing.Iterable[T]`"""
30
+ origin = get_origin(typ) or typ
31
+ return origin == Iterable or origin == _c_abc.Iterable
32
+
33
+
34
+ def is_union_type(typ: type) -> bool:
35
+ return _is_union(get_origin(typ))
36
+
37
+
38
+ def is_required_type(typ: type) -> bool:
39
+ return get_origin(typ) == Required
40
+
41
+
42
+ def is_typevar(typ: type) -> bool:
43
+ # type ignore is required because type checkers
44
+ # think this expression will always return False
45
+ return type(typ) == TypeVar # type: ignore
46
+
47
+
48
+ _TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (typing_extensions.TypeAliasType,)
49
+ if sys.version_info >= (3, 12):
50
+ _TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType)
51
+
52
+
53
+ def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]:
54
+ """Return whether the provided argument is an instance of `TypeAliasType`.
55
+
56
+ ```python
57
+ type Int = int
58
+ is_type_alias_type(Int)
59
+ # > True
60
+ Str = TypeAliasType("Str", str)
61
+ is_type_alias_type(Str)
62
+ # > True
63
+ ```
64
+ """
65
+ return isinstance(tp, _TYPE_ALIAS_TYPES)
66
+
67
+
68
+ # Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]]
69
+ def strip_annotated_type(typ: type) -> type:
70
+ if is_required_type(typ) or is_annotated_type(typ):
71
+ return strip_annotated_type(cast(type, get_args(typ)[0]))
72
+
73
+ return typ
74
+
75
+
76
+ def extract_type_arg(typ: type, index: int) -> type:
77
+ args = get_args(typ)
78
+ try:
79
+ return cast(type, args[index])
80
+ except IndexError as err:
81
+ raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err
82
+
83
+
84
+ def extract_type_var_from_base(
85
+ typ: type,
86
+ *,
87
+ generic_bases: tuple[type, ...],
88
+ index: int,
89
+ failure_message: str | None = None,
90
+ ) -> type:
91
+ """Given a type like `Foo[T]`, returns the generic type variable `T`.
92
+
93
+ This also handles the case where a concrete subclass is given, e.g.
94
+ ```py
95
+ class MyResponse(Foo[bytes]):
96
+ ...
97
+
98
+ extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes
99
+ ```
100
+
101
+ And where a generic subclass is given:
102
+ ```py
103
+ _T = TypeVar('_T')
104
+ class MyResponse(Foo[_T]):
105
+ ...
106
+
107
+ extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes
108
+ ```
109
+ """
110
+ cls = cast(object, get_origin(typ) or typ)
111
+ if cls in generic_bases:
112
+ # we're given the class directly
113
+ return extract_type_arg(typ, index)
114
+
115
+ # if a subclass is given
116
+ # ---
117
+ # this is needed as __orig_bases__ is not present in the typeshed stubs
118
+ # because it is intended to be for internal use only, however there does
119
+ # not seem to be a way to resolve generic TypeVars for inherited subclasses
120
+ # without using it.
121
+ if isinstance(cls, InheritsGeneric):
122
+ target_base_class: Any | None = None
123
+ for base in cls.__orig_bases__:
124
+ if base.__origin__ in generic_bases:
125
+ target_base_class = base
126
+ break
127
+
128
+ if target_base_class is None:
129
+ raise RuntimeError(
130
+ "Could not find the generic base class;\n"
131
+ "This should never happen;\n"
132
+ f"Does {cls} inherit from one of {generic_bases} ?"
133
+ )
134
+
135
+ extracted = extract_type_arg(target_base_class, index)
136
+ if is_typevar(extracted):
137
+ # If the extracted type argument is itself a type variable
138
+ # then that means the subclass itself is generic, so we have
139
+ # to resolve the type argument from the class itself, not
140
+ # the base class.
141
+ #
142
+ # Note: if there is more than 1 type argument, the subclass could
143
+ # change the ordering of the type arguments, this is not currently
144
+ # supported.
145
+ return extract_type_arg(typ, index)
146
+
147
+ return extracted
148
+
149
+ raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}")