-
-
Notifications
You must be signed in to change notification settings - Fork 621
Expand file tree
/
Copy pathbase.py
More file actions
493 lines (367 loc) · 15.2 KB
/
base.py
File metadata and controls
493 lines (367 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
from __future__ import annotations
import dataclasses
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Annotated,
Any,
ClassVar,
Generic,
Literal,
TypeGuard,
TypeVar,
get_origin,
overload,
)
from typing_extensions import Protocol, Self
from strawberry.utils.inspect import get_specialized_type_var_map
from strawberry.utils.typing import is_concrete_generic
from strawberry.utils.typing import is_generic as is_type_generic
if TYPE_CHECKING:
from collections.abc import Callable, Mapping, Sequence
from graphql import GraphQLAbstractType, GraphQLResolveInfo
from strawberry.types.field import StrawberryField
class StrawberryType(ABC):
"""The base class for all types that Strawberry uses.
Every type that is decorated by strawberry should have a dunder
`__strawberry_definition__` with an instance of a StrawberryType that contains
the parsed information that strawberry created.
NOTE: ATM this is only true for @type @interface @input follow
https://github.com/strawberry-graphql/strawberry/issues/2841 to see progress.
"""
@property
def type_params(self) -> list[TypeVar]:
return []
@property
def is_one_of(self) -> bool:
return False
@abstractmethod
def copy_with(
self,
type_var_map: Mapping[
str, StrawberryType | type[WithStrawberryObjectDefinition]
],
) -> StrawberryType | type[WithStrawberryObjectDefinition]:
raise NotImplementedError
@property
@abstractmethod
def is_graphql_generic(self) -> bool:
raise NotImplementedError
def has_generic(self, type_var: TypeVar) -> bool:
return False
def __eq__(self, other: object) -> bool:
from strawberry.annotation import StrawberryAnnotation
if isinstance(other, StrawberryType):
return self is other
if isinstance(other, StrawberryAnnotation):
return self == other.resolve()
# This could be simplified if StrawberryAnnotation.resolve() always returned
# a StrawberryType
resolved = StrawberryAnnotation(other).resolve()
if isinstance(resolved, StrawberryType):
return self == resolved
return NotImplemented
def __hash__(self) -> int:
# TODO: Is this a bad idea? __eq__ objects are supposed to have the same hash
return id(self)
class StrawberryContainer(StrawberryType):
def __init__(
self, of_type: StrawberryType | type[WithStrawberryObjectDefinition] | type
) -> None:
self.of_type = of_type
def __hash__(self) -> int:
return hash((self.__class__, self.of_type))
def __eq__(self, other: object) -> bool:
if isinstance(other, StrawberryType):
if isinstance(other, StrawberryContainer):
return self.of_type == other.of_type
return False
return super().__eq__(other)
@property
def type_params(self) -> list[TypeVar]:
if has_object_definition(self.of_type):
parameters = getattr(self.of_type, "__parameters__", None)
return list(parameters) if parameters else []
if isinstance(self.of_type, StrawberryType):
return self.of_type.type_params
return []
def copy_with(
self,
type_var_map: Mapping[
str, StrawberryType | type[WithStrawberryObjectDefinition]
],
) -> Self:
of_type_copy = self.of_type
if has_object_definition(self.of_type):
type_definition = self.of_type.__strawberry_definition__
if type_definition.is_graphql_generic:
of_type_copy = type_definition.copy_with(type_var_map)
elif (
isinstance(self.of_type, StrawberryType) and self.of_type.is_graphql_generic
):
of_type_copy = self.of_type.copy_with(type_var_map)
if get_origin(of_type_copy) is Annotated:
from strawberry.annotation import StrawberryAnnotation
of_type_copy = StrawberryAnnotation(of_type_copy).resolve()
return type(self)(of_type_copy)
@property
def is_graphql_generic(self) -> bool:
from strawberry.schema.compat import is_graphql_generic
type_ = self.of_type
return is_graphql_generic(type_)
def has_generic(self, type_var: TypeVar) -> bool:
if isinstance(self.of_type, StrawberryType):
return self.of_type.has_generic(type_var)
return False
class StrawberryList(StrawberryContainer): ...
class StrawberryOptional(StrawberryContainer):
def __init__(
self,
of_type: StrawberryType | type[WithStrawberryObjectDefinition] | type,
) -> None:
super().__init__(of_type)
class StrawberryMaybe(StrawberryOptional):
pass
class StrawberryTypeVar(StrawberryType):
def __init__(self, type_var: TypeVar) -> None:
self.type_var = type_var
def copy_with(
self, type_var_map: Mapping[str, StrawberryType | type]
) -> StrawberryType | type:
return type_var_map[self.type_var.__name__]
@property
def is_graphql_generic(self) -> bool:
return True
def has_generic(self, type_var: TypeVar) -> bool:
return self.type_var == type_var
@property
def type_params(self) -> list[TypeVar]:
return [self.type_var]
def __eq__(self, other: object) -> bool:
if isinstance(other, StrawberryTypeVar):
return self.type_var == other.type_var
if isinstance(other, TypeVar):
return self.type_var == other
return super().__eq__(other)
def __hash__(self) -> int:
return hash(self.type_var)
StrawberryDefinitionType = TypeVar("StrawberryDefinitionType")
class WithStrawberryDefinition(Protocol, Generic[StrawberryDefinitionType]):
__strawberry_definition__: ClassVar[StrawberryDefinitionType]
WithStrawberryObjectDefinition = WithStrawberryDefinition["StrawberryObjectDefinition"]
def has_strawberry_definition(
obj: Any,
) -> TypeGuard[type[WithStrawberryDefinition]]:
if hasattr(obj, "__strawberry_definition__"):
return True
# TODO: Generics remove dunder members here, so we inject it here.
# Would be better to avoid it somehow.
# https://github.com/python/cpython/blob/3a314f7c3df0dd7c37da7d12b827f169ee60e1ea/Lib/typing.py#L1152
if is_concrete_generic(obj):
concrete = obj.__origin__
if hasattr(concrete, "__strawberry_definition__"):
obj.__strawberry_definition__ = concrete.__strawberry_definition__
return True
return False
def has_object_definition(obj: Any) -> TypeGuard[type[WithStrawberryObjectDefinition]]:
if has_strawberry_definition(obj):
return isinstance(obj.__strawberry_definition__, StrawberryObjectDefinition)
return False
@overload
def get_object_definition(
obj: Any,
*,
strict: Literal[True],
) -> StrawberryObjectDefinition: ...
@overload
def get_object_definition(
obj: Any,
*,
strict: bool = False,
) -> StrawberryObjectDefinition | None: ...
def get_object_definition(
obj: Any,
*,
strict: bool = False,
) -> StrawberryObjectDefinition | None:
definition = obj.__strawberry_definition__ if has_object_definition(obj) else None
if strict and definition is None:
raise TypeError(f"{obj!r} does not have a StrawberryObjectDefinition")
return definition
@dataclasses.dataclass(eq=False)
class StrawberryObjectDefinition(StrawberryType):
"""Encapsulates definitions for Input / Object / interface GraphQL Types.
In order get the definition from a decorated object you can use
`has_object_definition` or `get_object_definition` as a shortcut.
"""
name: str
is_input: bool
is_interface: bool
origin: type[Any]
description: str | None
interfaces: list[StrawberryObjectDefinition]
extend: bool
directives: Sequence[object] | None
is_type_of: Callable[[Any, GraphQLResolveInfo], bool] | None
resolve_type: Callable[[Any, GraphQLResolveInfo, GraphQLAbstractType], str] | None
fields: list[StrawberryField]
concrete_of: StrawberryObjectDefinition | None = None
"""Concrete implementations of Generic TypeDefinitions fill this in"""
type_var_map: Mapping[str, StrawberryType | type] = dataclasses.field(
default_factory=dict
)
def __post_init__(self) -> None:
# resolve `Self` annotation with the origin type
for index, field in enumerate(self.fields):
if isinstance(field.type, StrawberryType) and field.type.has_generic(Self): # type: ignore
self.fields[index] = field.copy_with({Self.__name__: self.origin}) # type: ignore
def resolve_generic(self, wrapped_cls: type) -> type:
from strawberry.annotation import StrawberryAnnotation
passed_types = wrapped_cls.__args__ # type: ignore
params = wrapped_cls.__origin__.__parameters__ # type: ignore
# Make sure all passed_types are turned into StrawberryTypes
resolved_types = []
for passed_type in passed_types:
resolved_type = StrawberryAnnotation(passed_type).resolve()
resolved_types.append(resolved_type)
type_var_map = dict(
zip((param.__name__ for param in params), resolved_types, strict=True)
)
return self.copy_with(type_var_map)
def copy_with(
self, type_var_map: Mapping[str, StrawberryType | type]
) -> type[WithStrawberryObjectDefinition]:
fields = [field.copy_with(type_var_map) for field in self.fields]
new_type_definition = StrawberryObjectDefinition(
name=self.name,
is_input=self.is_input,
origin=self.origin,
is_interface=self.is_interface,
directives=self.directives and self.directives[:],
interfaces=self.interfaces and self.interfaces[:],
description=self.description,
extend=self.extend,
is_type_of=self.is_type_of,
resolve_type=self.resolve_type,
fields=fields,
concrete_of=self,
type_var_map=type_var_map,
)
new_type = type(
new_type_definition.name,
(self.origin,),
{"__strawberry_definition__": new_type_definition},
)
new_type_definition.origin = new_type
return new_type
def get_field(self, python_name: str) -> StrawberryField | None:
return next(
(field for field in self.fields if field.python_name == python_name), None
)
@property
def is_graphql_generic(self) -> bool:
if not is_type_generic(self.origin):
return False
# here we are checking if any exposed field is generic
# a Strawberry class can be "generic", but not expose any
# generic field to GraphQL
return any(field.is_graphql_generic for field in self.fields)
@property
def is_specialized_generic(self) -> bool:
return self.is_graphql_generic and not getattr(
self.origin, "__parameters__", None
)
@property
def specialized_type_var_map(self) -> dict[str, type] | None:
return get_specialized_type_var_map(self.origin)
@property
def is_object_type(self) -> bool:
return not self.is_input and not self.is_interface
@property
def type_params(self) -> list[TypeVar]:
type_params: list[TypeVar] = []
for field in self.fields:
type_params.extend(field.type_params)
return type_params
def is_implemented_by(self, root: type[WithStrawberryObjectDefinition]) -> bool:
# TODO: Support dicts
if isinstance(root, dict):
raise NotImplementedError
type_definition = root.__strawberry_definition__
if type_definition is self:
# No generics involved. Exact type match
return True
if type_definition is not self.concrete_of:
# Either completely different type, or concrete type of a different generic
return False
# Check the mapping of all fields' TypeVars
for field in type_definition.fields:
if not field.is_graphql_generic:
continue
value = getattr(root, field.name)
generic_field_type = field.type
while isinstance(generic_field_type, StrawberryList):
generic_field_type = generic_field_type.of_type
assert isinstance(value, (list, tuple))
if len(value) == 0:
# We can't infer the type of an empty list, so we just
# return the first one we find
return True
value = value[0]
if isinstance(generic_field_type, StrawberryTypeVar):
type_var = generic_field_type.type_var
# TODO: I don't think we support nested types properly
# if there's a union that has two nested types that
# are have the same field with different types, we might
# not be able to differentiate them
else:
continue
# For each TypeVar found, get the expected type from the copy's type map
expected_concrete_type = self.type_var_map.get(type_var.__name__)
# this shouldn't happen, but we do a defensive check just in case
if expected_concrete_type is None:
continue
# Check if the expected type matches the type found on the type_map
from strawberry.types.enum import (
StrawberryEnumDefinition,
has_enum_definition,
)
real_concrete_type: type | StrawberryEnumDefinition = type(value)
# TODO: uniform type var map, at the moment we map object types
# to their class (not to TypeDefinition) while we map enum to
# the StrawberryEnumDefinition class. This is why we do this check here:
if has_enum_definition(real_concrete_type):
real_concrete_type = real_concrete_type.__strawberry_definition__
if (
isinstance(expected_concrete_type, type)
and isinstance(real_concrete_type, type)
and issubclass(real_concrete_type, expected_concrete_type)
):
return True
from strawberry.types.union import StrawberryUnion
if (
isinstance(expected_concrete_type, StrawberryUnion)
and real_concrete_type in expected_concrete_type.types
):
return True
if real_concrete_type is not expected_concrete_type:
return False
# All field mappings succeeded. This is a match
return True
@property
def is_one_of(self) -> bool:
from strawberry.schema_directives import OneOf
if not self.is_input or not self.directives:
return False
return any(isinstance(directive, OneOf) for directive in self.directives)
__all__ = [
"StrawberryContainer",
"StrawberryList",
"StrawberryObjectDefinition",
"StrawberryOptional",
"StrawberryType",
"StrawberryTypeVar",
"WithStrawberryObjectDefinition",
"get_object_definition",
"has_object_definition",
]