graphql-python / graphql-core

A Python 3.6+ port of the GraphQL.js reference implementation of GraphQL.
MIT License
512 stars 136 forks source link

Use type guards #183

Closed helderco closed 2 years ago

helderco commented 2 years ago

As an example I specifically need them in type/definition.py to correctly narrow down the types in a codegen tool. In the meantime I've reimplemented these functions:

def is_required_type(t: Any) -> TypeGuard[GraphQLNonNull]:
    return isinstance(t, GraphQLNonNull)

def is_list_type(t: Any) -> TypeGuard[GraphQLList]:
    return isinstance(t, GraphQLList)

def is_wrapping_type(t: Any) -> TypeGuard[GraphQLWrappingType]:
    return isinstance(t, GraphQLWrappingType)

def is_scalar_type(t: Any) -> TypeGuard[GraphQLScalarType]:
    return isinstance(t, GraphQLScalarType)

def is_input_object_type(t: Any) -> TypeGuard[GraphQLInputObjectType]:
    return isinstance(t, GraphQLInputObjectType)

def is_object_type(t: Any) -> TypeGuard[GraphQLObjectType]:
    return isinstance(t, GraphQLObjectType)

I thought the isinstance would be enough for the type checker to infer in these cases but if the return type is bool in these functions they're not narrowed.

Cito commented 2 years ago

Thanks for reminding me of this feature @helderco, we should definitely do that. Though it's only available since Python 3.10, it also can be used in earlier Python versions via typing-extensions.

Cito commented 2 years ago

Commited to the main branch, will be available in the next (alpha) release of version 3.3.

Cito commented 2 years ago

Available now in v3.3.0a2.