Skip to content

Commit 7b9e922

Browse files
committed
Fix ruff issues
1 parent 41799bb commit 7b9e922

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+211
-187
lines changed

src/graphql/execution/collect_fields.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ def build_grouped_field_sets(
394394
# All TargetSets that causes new grouped field sets consist only of DeferUsages
395395
# and have should_initiate_defer defined
396396

397-
new_grouped_field_set_details[cast(DeferUsageSet, masking_targets)] = (
397+
new_grouped_field_set_details[cast("DeferUsageSet", masking_targets)] = (
398398
GroupedFieldSetDetails(new_grouped_field_set, should_initiate_defer)
399399
)
400400

src/graphql/execution/execute.py

+13-11
Original file line numberDiff line numberDiff line change
@@ -975,7 +975,7 @@ def complete_list_value(
975975

976976
if stream_record is not None:
977977
self.incremental_publisher.set_is_final_record(
978-
cast(StreamItemsRecord, current_parents)
978+
cast("StreamItemsRecord", current_parents)
979979
)
980980

981981
if not awaitable_indices:
@@ -1113,7 +1113,7 @@ def complete_abstract_value(
11131113
runtime_type = resolve_type_fn(result, info, return_type)
11141114

11151115
if self.is_awaitable(runtime_type):
1116-
runtime_type = cast(Awaitable, runtime_type)
1116+
runtime_type = cast("Awaitable", runtime_type)
11171117

11181118
async def await_complete_object_value() -> Any:
11191119
value = self.complete_object_value(
@@ -1136,7 +1136,7 @@ async def await_complete_object_value() -> Any:
11361136
return value # pragma: no cover
11371137

11381138
return await_complete_object_value()
1139-
runtime_type = cast(Optional[str], runtime_type)
1139+
runtime_type = cast("Optional[str]", runtime_type)
11401140

11411141
return self.complete_object_value(
11421142
self.ensure_valid_runtime_type(
@@ -1358,9 +1358,9 @@ async def callback(payload: Any) -> ExecutionResult:
13581358
# typecast to ExecutionResult, not possible to return
13591359
# ExperimentalIncrementalExecutionResults when operation is 'subscription'.
13601360
return (
1361-
await cast(Awaitable[ExecutionResult], result)
1361+
await cast("Awaitable[ExecutionResult]", result)
13621362
if self.is_awaitable(result)
1363-
else cast(ExecutionResult, result)
1363+
else cast("ExecutionResult", result)
13641364
)
13651365

13661366
return map_async_iterable(result_or_stream, callback)
@@ -1424,7 +1424,7 @@ def execute_deferred_grouped_field_set(
14241424
)
14251425

14261426
if self.is_awaitable(incremental_result):
1427-
incremental_result = cast(Awaitable, incremental_result)
1427+
incremental_result = cast("Awaitable", incremental_result)
14281428

14291429
async def await_incremental_result() -> None:
14301430
try:
@@ -1897,11 +1897,11 @@ def execute_sync(
18971897
result, ExperimentalIncrementalExecutionResults
18981898
):
18991899
if default_is_awaitable(result):
1900-
ensure_future(cast(Awaitable[ExecutionResult], result)).cancel()
1900+
ensure_future(cast("Awaitable[ExecutionResult]", result)).cancel()
19011901
msg = "GraphQL execution failed to complete synchronously."
19021902
raise RuntimeError(msg)
19031903

1904-
return cast(ExecutionResult, result)
1904+
return cast("ExecutionResult", result)
19051905

19061906

19071907
def invalid_return_type_error(
@@ -1956,7 +1956,9 @@ def add_new_deferred_fragments(
19561956
# - the InitialResultRecord, or
19571957
# - a StreamItemsRecord, as `@defer` may be nested under `@stream`.
19581958
parent = (
1959-
cast(Union[InitialResultRecord, StreamItemsRecord], incremental_data_record)
1959+
cast(
1960+
"Union[InitialResultRecord, StreamItemsRecord]", incremental_data_record
1961+
)
19601962
if parent_defer_usage is None
19611963
else deferred_fragment_record_from_defer_usage(
19621964
parent_defer_usage, new_defer_map
@@ -2069,7 +2071,7 @@ def default_type_resolver(
20692071
is_type_of_result = type_.is_type_of(value, info)
20702072

20712073
if is_awaitable(is_type_of_result):
2072-
append_awaitable_results(cast(Awaitable, is_type_of_result))
2074+
append_awaitable_results(cast("Awaitable", is_type_of_result))
20732075
append_awaitable_types(type_)
20742076
elif is_type_of_result:
20752077
return type_.name
@@ -2257,7 +2259,7 @@ def create_source_event_stream_impl(
22572259
return ExecutionResult(None, errors=[error])
22582260

22592261
if context.is_awaitable(event_stream):
2260-
awaitable_event_stream = cast(Awaitable, event_stream)
2262+
awaitable_event_stream = cast("Awaitable", event_stream)
22612263

22622264
# noinspection PyShadowingNames
22632265
async def await_event_stream() -> AsyncIterable[Any] | ExecutionResult:

src/graphql/graphql.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,9 @@ async def graphql(
9696
)
9797

9898
if default_is_awaitable(result):
99-
return await cast(Awaitable[ExecutionResult], result)
99+
return await cast("Awaitable[ExecutionResult]", result)
100100

101-
return cast(ExecutionResult, result)
101+
return cast("ExecutionResult", result)
102102

103103

104104
def assume_not_awaitable(_value: Any) -> bool:
@@ -149,11 +149,11 @@ def graphql_sync(
149149

150150
# Assert that the execution was synchronous.
151151
if default_is_awaitable(result):
152-
ensure_future(cast(Awaitable[ExecutionResult], result)).cancel()
152+
ensure_future(cast("Awaitable[ExecutionResult]", result)).cancel()
153153
msg = "GraphQL execution failed to complete synchronously."
154154
raise RuntimeError(msg)
155155

156-
return cast(ExecutionResult, result)
156+
return cast("ExecutionResult", result)
157157

158158

159159
def graphql_impl(

src/graphql/language/parser.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ def __init__(
255255
experimental_client_controlled_nullability: bool = False,
256256
) -> None:
257257
if not is_source(source):
258-
source = Source(cast(str, source))
258+
source = Source(cast("str", source))
259259

260260
self._no_location = no_location
261261
self._max_tokens = max_tokens
@@ -319,7 +319,7 @@ def parse_definition(self) -> DefinitionNode:
319319
)
320320

321321
if keyword_token.kind is TokenKind.NAME:
322-
token_name = cast(str, keyword_token.value)
322+
token_name = cast("str", keyword_token.value)
323323
method_name = self._parse_type_system_definition_method_names.get(
324324
token_name
325325
)
@@ -472,7 +472,9 @@ def parse_arguments(self, is_const: bool) -> list[ArgumentNode]:
472472
"""Arguments[Const]: (Argument[?Const]+)"""
473473
item = self.parse_const_argument if is_const else self.parse_argument
474474
return self.optional_many(
475-
TokenKind.PAREN_L, cast(Callable[[], ArgumentNode], item), TokenKind.PAREN_R
475+
TokenKind.PAREN_L,
476+
cast("Callable[[], ArgumentNode]", item),
477+
TokenKind.PAREN_R,
476478
)
477479

478480
def parse_argument(self, is_const: bool = False) -> ArgumentNode:
@@ -487,7 +489,7 @@ def parse_argument(self, is_const: bool = False) -> ArgumentNode:
487489

488490
def parse_const_argument(self) -> ConstArgumentNode:
489491
"""Argument[Const]: Name : Value[Const]"""
490-
return cast(ConstArgumentNode, self.parse_argument(True))
492+
return cast("ConstArgumentNode", self.parse_argument(True))
491493

492494
# Implement the parsing rules in the Fragments section.
493495

@@ -641,7 +643,7 @@ def parse_variable_value(self, is_const: bool) -> VariableNode:
641643
return self.parse_variable()
642644

643645
def parse_const_value_literal(self) -> ConstValueNode:
644-
return cast(ConstValueNode, self.parse_value_literal(True))
646+
return cast("ConstValueNode", self.parse_value_literal(True))
645647

646648
# Implement the parsing rules in the Directives section.
647649

@@ -654,7 +656,7 @@ def parse_directives(self, is_const: bool) -> list[DirectiveNode]:
654656
return directives
655657

656658
def parse_const_directives(self) -> list[ConstDirectiveNode]:
657-
return cast(List[ConstDirectiveNode], self.parse_directives(True))
659+
return cast("List[ConstDirectiveNode]", self.parse_directives(True))
658660

659661
def parse_directive(self, is_const: bool) -> DirectiveNode:
660662
"""Directive[Const]: @ Name Arguments[?Const]?"""
@@ -704,7 +706,7 @@ def parse_type_system_extension(self) -> TypeSystemExtensionNode:
704706
keyword_token = self._lexer.lookahead()
705707
if keyword_token.kind == TokenKind.NAME:
706708
method_name = self._parse_type_extension_method_names.get(
707-
cast(str, keyword_token.value)
709+
cast("str", keyword_token.value)
708710
)
709711
if method_name: # pragma: no cover
710712
return getattr(self, f"parse_{method_name}")()

src/graphql/language/print_location.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def print_source_location(source: Source, source_location: SourceLocation) -> st
7373
def print_prefixed_lines(*lines: tuple[str, str | None]) -> str:
7474
"""Print lines specified like this: ("prefix", "string")"""
7575
existing_lines = [
76-
cast(Tuple[str, str], line) for line in lines if line[1] is not None
76+
cast("Tuple[str, str]", line) for line in lines if line[1] is not None
7777
]
7878
pad_len = max(len(line[0]) for line in existing_lines)
7979
return "\n".join(

src/graphql/pyutils/async_reduce.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ async def async_callback(
4141
)
4242
return await result if is_awaitable(result) else result # type: ignore
4343

44-
accumulator = async_callback(cast(Awaitable[U], accumulator), value)
44+
accumulator = async_callback(cast("Awaitable[U]", accumulator), value)
4545
else:
46-
accumulator = callback(cast(U, accumulator), value)
46+
accumulator = callback(cast("U", accumulator), value)
4747
return accumulator

src/graphql/pyutils/identity_func.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
T = TypeVar("T")
1313

14-
DEFAULT_VALUE = cast(Any, Undefined)
14+
DEFAULT_VALUE = cast("Any", Undefined)
1515

1616

1717
def identity_func(x: T = DEFAULT_VALUE, *_args: Any) -> T:

src/graphql/pyutils/merge_kwargs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@
99

1010
def merge_kwargs(base_dict: T, **kwargs: Any) -> T:
1111
"""Return arbitrary typed dictionary with some keyword args merged in."""
12-
return cast(T, {**cast(Dict, base_dict), **kwargs})
12+
return cast("T", {**cast("Dict", base_dict), **kwargs})

src/graphql/type/definition.py

+19-16
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from __future__ import annotations
44

5-
from enum import Enum
65
from typing import (
76
TYPE_CHECKING,
87
Any,
@@ -19,6 +18,18 @@
1918
overload,
2019
)
2120

21+
try:
22+
from typing import TypedDict
23+
except ImportError: # Python < 3.8
24+
from typing_extensions import TypedDict
25+
try:
26+
from typing import TypeAlias, TypeGuard
27+
except ImportError: # Python < 3.10
28+
from typing_extensions import TypeAlias, TypeGuard
29+
30+
if TYPE_CHECKING:
31+
from enum import Enum
32+
2233
from ..error import GraphQLError
2334
from ..language import (
2435
EnumTypeDefinitionNode,
@@ -57,18 +68,10 @@
5768
from ..utilities.value_from_ast_untyped import value_from_ast_untyped
5869
from .assert_name import assert_enum_value_name, assert_name
5970

60-
try:
61-
from typing import TypedDict
62-
except ImportError: # Python < 3.8
63-
from typing_extensions import TypedDict
64-
try:
65-
from typing import TypeAlias, TypeGuard
66-
except ImportError: # Python < 3.10
67-
from typing_extensions import TypeAlias, TypeGuard
68-
6971
if TYPE_CHECKING:
7072
from .schema import GraphQLSchema
7173

74+
7275
__all__ = [
7376
"GraphQLAbstractType",
7477
"GraphQLArgument",
@@ -503,7 +506,7 @@ def __init__(
503506
args = {
504507
assert_name(name): value
505508
if isinstance(value, GraphQLArgument)
506-
else GraphQLArgument(cast(GraphQLInputType, value))
509+
else GraphQLArgument(cast("GraphQLInputType", value))
507510
for name, value in args.items()
508511
}
509512
else:
@@ -1077,7 +1080,7 @@ def __init__(
10771080
extension_ast_nodes=extension_ast_nodes,
10781081
)
10791082
try: # check for enum
1080-
values = cast(Enum, values).__members__ # type: ignore
1083+
values = cast("Enum", values).__members__ # type: ignore
10811084
except AttributeError:
10821085
if not isinstance(values, Mapping) or not all(
10831086
isinstance(name, str) for name in values
@@ -1090,9 +1093,9 @@ def __init__(
10901093
" with value names as keys."
10911094
)
10921095
raise TypeError(msg) from error
1093-
values = cast(Dict[str, Any], values)
1096+
values = cast("Dict[str, Any]", values)
10941097
else:
1095-
values = cast(Dict[str, Enum], values)
1098+
values = cast("Dict[str, Enum]", values)
10961099
if names_as_values is False:
10971100
values = {key: value.value for key, value in values.items()}
10981101
elif names_as_values is True:
@@ -1662,7 +1665,7 @@ def get_nullable_type(
16621665
"""Unwrap possible non-null type"""
16631666
if is_non_null_type(type_):
16641667
type_ = type_.of_type
1665-
return cast(Optional[GraphQLNullableType], type_)
1668+
return cast("Optional[GraphQLNullableType]", type_)
16661669

16671670

16681671
# These named types do not include modifiers like List or NonNull.
@@ -1707,7 +1710,7 @@ def get_named_type(type_: GraphQLType | None) -> GraphQLNamedType | None:
17071710
unwrapped_type = type_
17081711
while is_wrapping_type(unwrapped_type):
17091712
unwrapped_type = unwrapped_type.of_type
1710-
return cast(GraphQLNamedType, unwrapped_type)
1713+
return cast("GraphQLNamedType", unwrapped_type)
17111714
return None
17121715

17131716

src/graphql/type/directives.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def __init__(
7979
locations = tuple(
8080
value
8181
if isinstance(value, DirectiveLocation)
82-
else DirectiveLocation[cast(str, value)]
82+
else DirectiveLocation[cast("str", value)]
8383
for value in locations
8484
)
8585
except (KeyError, TypeError) as error:
@@ -92,7 +92,7 @@ def __init__(
9292
args = {
9393
assert_name(name): value
9494
if isinstance(value, GraphQLArgument)
95-
else GraphQLArgument(cast(GraphQLInputType, value))
95+
else GraphQLArgument(cast("GraphQLInputType", value))
9696
for name, value in args.items()
9797
}
9898
else:

src/graphql/type/schema.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -297,11 +297,12 @@ def __deepcopy__(self, memo_: dict) -> GraphQLSchema:
297297
for directive in directives:
298298
remap_directive(directive, type_map)
299299
return self.__class__(
300-
self.query_type and cast(GraphQLObjectType, type_map[self.query_type.name]),
300+
self.query_type
301+
and cast("GraphQLObjectType", type_map[self.query_type.name]),
301302
self.mutation_type
302-
and cast(GraphQLObjectType, type_map[self.mutation_type.name]),
303+
and cast("GraphQLObjectType", type_map[self.mutation_type.name]),
303304
self.subscription_type
304-
and cast(GraphQLObjectType, type_map[self.subscription_type.name]),
305+
and cast("GraphQLObjectType", type_map[self.subscription_type.name]),
305306
types,
306307
directives,
307308
self.description,
@@ -327,7 +328,7 @@ def get_possible_types(
327328
abstract_type.types
328329
if is_union_type(abstract_type)
329330
else self.get_implementations(
330-
cast(GraphQLInterfaceType, abstract_type)
331+
cast("GraphQLInterfaceType", abstract_type)
331332
).objects
332333
)
333334

@@ -354,7 +355,7 @@ def is_sub_type(
354355
add(type_.name)
355356
else:
356357
implementations = self.get_implementations(
357-
cast(GraphQLInterfaceType, abstract_type)
358+
cast("GraphQLInterfaceType", abstract_type)
358359
)
359360
for type_ in implementations.objects:
360361
add(type_.name)
@@ -410,7 +411,7 @@ class TypeSet(Dict[GraphQLNamedType, None]):
410411

411412
@classmethod
412413
def with_initial_types(cls, types: Collection[GraphQLType]) -> TypeSet:
413-
return cast(TypeSet, super().fromkeys(types))
414+
return cast("TypeSet", super().fromkeys(types))
414415

415416
def collect_referenced_types(self, type_: GraphQLType) -> None:
416417
"""Recursive function supplementing the type starting from an initial type."""
@@ -455,7 +456,7 @@ def remapped_type(type_: GraphQLType, type_map: TypeMap) -> GraphQLType:
455456
"""Get a copy of the given type that uses this type map."""
456457
if is_wrapping_type(type_):
457458
return type_.__class__(remapped_type(type_.of_type, type_map))
458-
type_ = cast(GraphQLNamedType, type_)
459+
type_ = cast("GraphQLNamedType", type_)
459460
return type_map.get(type_.name, type_)
460461

461462

@@ -493,5 +494,5 @@ def remap_directive(directive: GraphQLDirective, type_map: TypeMap) -> None:
493494
args = directive.args
494495
for arg_name, arg in args.items():
495496
arg = copy(arg) # noqa: PLW2901
496-
arg.type = cast(GraphQLInputType, remapped_type(arg.type, type_map))
497+
arg.type = cast("GraphQLInputType", remapped_type(arg.type, type_map))
497498
args[arg_name] = arg

0 commit comments

Comments
 (0)