|
2 | 2 | import copy |
3 | 3 | import dataclasses |
4 | 4 | import inspect |
| 5 | +import sys |
5 | 6 | import types |
6 | 7 | from collections.abc import Callable, Sequence |
7 | 8 | from typing import ( |
| 9 | + Annotated, |
8 | 10 | Any, |
| 11 | + ForwardRef, |
9 | 12 | TypeVar, |
10 | 13 | cast, |
| 14 | + get_args, |
| 15 | + get_origin, |
11 | 16 | overload, |
12 | 17 | ) |
13 | | -from typing_extensions import dataclass_transform, get_annotations |
| 18 | +from typing_extensions import ( |
| 19 | + Format, |
| 20 | + dataclass_transform, |
| 21 | + evaluate_forward_ref, |
| 22 | + get_annotations, |
| 23 | +) |
14 | 24 |
|
| 25 | +from strawberry.annotation import StrawberryAnnotation |
15 | 26 | from strawberry.exceptions import ( |
16 | 27 | InvalidSuperclassInterfaceError, |
17 | 28 | MissingFieldAnnotationError, |
18 | 29 | MissingReturnAnnotationError, |
| 30 | + MultipleStrawberryFieldsError, |
19 | 31 | ObjectIsNotClassError, |
20 | 32 | ) |
21 | 33 | from strawberry.types.base import get_object_definition |
|
30 | 42 | T = TypeVar("T", bound=builtins.type) |
31 | 43 |
|
32 | 44 |
|
| 45 | +def _process_annotated_fields(cls: T) -> dict[str, StrawberryAnnotation]: |
| 46 | + """Make StrawberryFields in Annotated available to dataclasses.""" |
| 47 | + module_namespace = sys.modules[cls.__module__].__dict__ |
| 48 | + type_annotations: dict[str, StrawberryAnnotation] = {} |
| 49 | + |
| 50 | + annotations = get_annotations(cls, format=Format.FORWARDREF) |
| 51 | + |
| 52 | + for field_name, raw_annotation in annotations.items(): |
| 53 | + annotation: object |
| 54 | + if isinstance(raw_annotation, str): |
| 55 | + try: |
| 56 | + annotation = evaluate_forward_ref( |
| 57 | + ForwardRef(raw_annotation), |
| 58 | + owner=cls, |
| 59 | + globals=module_namespace, |
| 60 | + locals=dict(vars(cls)), |
| 61 | + format=Format.FORWARDREF, |
| 62 | + ) |
| 63 | + if isinstance(annotation, ForwardRef): |
| 64 | + annotation = StrawberryAnnotation( |
| 65 | + raw_annotation, |
| 66 | + namespace=module_namespace, |
| 67 | + ).evaluate() |
| 68 | + except (NameError, TypeError): |
| 69 | + continue |
| 70 | + else: |
| 71 | + annotation = raw_annotation |
| 72 | + |
| 73 | + if get_origin(annotation) is not Annotated: |
| 74 | + continue |
| 75 | + |
| 76 | + first, *rest = get_args(annotation) |
| 77 | + strawberry_fields = [arg for arg in rest if isinstance(arg, StrawberryField)] |
| 78 | + |
| 79 | + if len(strawberry_fields) > 1 or ( |
| 80 | + strawberry_fields |
| 81 | + and isinstance(cls.__dict__.get(field_name), StrawberryField) |
| 82 | + ): |
| 83 | + raise MultipleStrawberryFieldsError(field_name=field_name, cls=cls) |
| 84 | + |
| 85 | + if not strawberry_fields: |
| 86 | + continue |
| 87 | + |
| 88 | + source_field = strawberry_fields[0] |
| 89 | + field = copy.copy(source_field) |
| 90 | + |
| 91 | + default = cls.__dict__.get(field_name, dataclasses.MISSING) |
| 92 | + if ( |
| 93 | + field.default is dataclasses.MISSING |
| 94 | + and field.default_factory is dataclasses.MISSING |
| 95 | + and default is not dataclasses.MISSING |
| 96 | + ): |
| 97 | + if isinstance(default, dataclasses.Field): |
| 98 | + field.default = default.default |
| 99 | + field.default_factory = default.default_factory |
| 100 | + if default.default is not dataclasses.MISSING: |
| 101 | + field.default_value = default.default |
| 102 | + elif callable(default.default_factory): |
| 103 | + field.default_value = default.default_factory() |
| 104 | + else: |
| 105 | + field.default = default |
| 106 | + field.default_value = default |
| 107 | + |
| 108 | + remaining_metadata = [ |
| 109 | + arg for arg in rest if not isinstance(arg, StrawberryField) |
| 110 | + ] |
| 111 | + field_type = ( |
| 112 | + field.type_annotation.raw_annotation |
| 113 | + if field.type_annotation is not None |
| 114 | + else first |
| 115 | + ) |
| 116 | + field_type = ( |
| 117 | + Annotated[(field_type, *remaining_metadata)] |
| 118 | + if remaining_metadata |
| 119 | + else field_type |
| 120 | + ) |
| 121 | + type_annotation = ( |
| 122 | + field.type_annotation |
| 123 | + if field.type_annotation is not None and not remaining_metadata |
| 124 | + else StrawberryAnnotation( |
| 125 | + field_type, |
| 126 | + namespace=( |
| 127 | + field.type_annotation.namespace |
| 128 | + if field.type_annotation is not None |
| 129 | + and field.type_annotation.namespace is not None |
| 130 | + else module_namespace |
| 131 | + ), |
| 132 | + ) |
| 133 | + ) |
| 134 | + field.type_annotation = type_annotation |
| 135 | + |
| 136 | + setattr(cls, field_name, field) |
| 137 | + type_annotations[field_name] = type_annotation |
| 138 | + |
| 139 | + return type_annotations |
| 140 | + |
| 141 | + |
33 | 142 | def _get_interfaces(cls: builtins.type[Any]) -> list[StrawberryObjectDefinition]: |
34 | 143 | interfaces: list[StrawberryObjectDefinition] = [] |
35 | 144 | for base in cls.__mro__[1:]: # Exclude current class |
@@ -108,9 +217,19 @@ def _check_field_annotations(cls: builtins.type[Any]) -> None: |
108 | 217 |
|
109 | 218 | def _wrap_dataclass(cls: T) -> T: |
110 | 219 | """Wrap a strawberry.type class with a dataclass and check for any issues before doing so.""" |
| 220 | + annotated_field_types = _process_annotated_fields(cls) |
| 221 | + |
111 | 222 | # Ensure all Fields have been properly type-annotated |
112 | 223 | _check_field_annotations(cls) |
113 | | - return cast("T", dataclasses.dataclass(kw_only=True)(cls)) |
| 224 | + wrapped = cast("T", dataclasses.dataclass(kw_only=True)(cls)) |
| 225 | + |
| 226 | + # dataclasses replaces each StrawberryField's type with the class annotation. |
| 227 | + # Restore the type with only the StrawberryField metadata removed, keeping any |
| 228 | + # other Annotated metadata and explicit graphql_type override intact. |
| 229 | + for field_name, type_annotation in annotated_field_types.items(): |
| 230 | + wrapped.__dataclass_fields__[field_name].type_annotation = type_annotation # type: ignore[attr-defined] |
| 231 | + |
| 232 | + return wrapped |
114 | 233 |
|
115 | 234 |
|
116 | 235 | def _inject_default_for_maybe_annotations(cls: T, annotations: dict[str, Any]) -> None: |
|
0 commit comments