Generics
Strawberry supports using Pythonβs Generic
typing to dynamically create
reusable types.
Strawberry will automatically generate the correct GraphQL schema from the combination of the generic type and the type arguments. Generics are supported in Object types, Input types, and Arguments to queries, mutations, and scalars.
Letβs take a look at an example:
Object Types
This example defines a generic type Page
that can be used to represent a page
of any type. For example, we can create a page of User
objects:
It is also possible to use a specialized generic type directly. For example, the same example above could be written like this:
Input and Argument Types
Arguments to queries and mutations can also be made generic by creating Generic Input types. Here weβll define an input type that can serve as a collection of anything, then create a specialization by using as a filled-in argument on a mutation.
Note: Pay attention to the fact that both
CollectionInput
andPostInput
are Input types. Providingposts: CollectionInput[Post]
toadd_posts
(i.e. using the non-inputPost
type) would have resulted in an error:
Multiple Specializations
Using multiple specializations of a Generic type will work as expected. Here we
define a Point2D
type and then specialize it for both int
s and float
s.
Variadic Generics
Variadic Generics, introduced in PEP-646 , are currently unsupported.