strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.01k stars 533 forks source link

Rename generic types on the fly #2131

Open benzolium opened 2 years ago

benzolium commented 2 years ago

It would be nice to rename generic types by annotating them.

E.g. with typing.Annotated like for arguments.

My use case is to annotate generic types inside the union:

import strawberry
import typing as tp

GenericType = tp.TypeVar('GenericType')

@strawberry.type(name='SomeGeneric')
class SomeGenericType(
    tp.Generic[GenericType]
):
    value: GenericType

SomeType = strawberry.union(
    name='SomeTypeName',
    types=(
        tp.Annotated[SomeGenericType[int], strawberry.type(name='SomeGenericTypeInt')],
        tp.Annotated[SomeGenericType[float], strawberry.type(name='SomeGenericTypeFloat')],
    )
)

@strawberry.type
class Query:
    @strawberry.field
    def user(self) -> tp.Optional[SomeType]:
        return None

schema = strawberry.Schema(query=Query)

Upvote & Fund

Fund with Polar

nrbnlulu commented 2 years ago

May be resolved by #2117 Where generics are evaluated by __getitem__(annotations) users would be able to do:

SomeGenericTypeInt = SomeGenericType[int]
SomeGenericTypeInt._type_definition.graphql_name = "SomeGenericTypeInt"

or we would provide some helper function for renaming a type that will do this.

strawberry.tools.rename_type(SomeGenericTypeInt, "SomeGenericTypeInt")