Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ANN401: Replace Any #3526

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions strawberry/aiohttp/handlers/graphql_transport_ws_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Callable, Dict
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional

from aiohttp import http, web
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL
Expand All @@ -11,6 +11,7 @@
if TYPE_CHECKING:
from datetime import timedelta

from strawberry.http.typevars import RootValue
from strawberry.schema import BaseSchema


Expand All @@ -21,7 +22,7 @@ def __init__(
debug: bool,
connection_init_wait_timeout: timedelta,
get_context: Callable[..., Dict[str, Any]],
get_root_value: Any,
get_root_value: Callable[..., Optional[RootValue]],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mmh, I think we don't need Optional here 🤔 (same below)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added Optional because of this implementation, is it wrong?

async def get_root_value(self, request: ChannelsConsumer) -> Optional[RootValue]:
return None

request: web.Request,
) -> None:
super().__init__(schema, debug, connection_init_wait_timeout)
Expand All @@ -30,10 +31,10 @@ def __init__(
self._request = request
self._ws = web.WebSocketResponse(protocols=[GRAPHQL_TRANSPORT_WS_PROTOCOL])

async def get_context(self) -> Any:
async def get_context(self) -> Dict[str, Any]:
return await self._get_context(request=self._request, response=self._ws) # type: ignore

async def get_root_value(self) -> Any:
async def get_root_value(self) -> Optional[RootValue]:
return await self._get_root_value(request=self._request)

async def send_json(self, data: dict) -> None:
Expand Down
28 changes: 14 additions & 14 deletions strawberry/annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
import typing
from collections import abc
from enum import Enum
from enum import Enum, EnumMeta
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -179,13 +179,13 @@ def create_concrete_type(self, evaled_type: type) -> type:
return evaled_type.__strawberry_definition__.resolve_generic(evaled_type)
raise ValueError(f"Not supported {evaled_type}")

def create_enum(self, evaled_type: Any) -> EnumDefinition:
def create_enum(self, evaled_type: EnumMeta) -> EnumDefinition:
patrick91 marked this conversation as resolved.
Show resolved Hide resolved
try:
return evaled_type._enum_definition
except AttributeError:
raise NotAStrawberryEnumError(evaled_type)

def create_list(self, evaled_type: Any) -> StrawberryList:
def create_list(self, evaled_type: type) -> StrawberryList:
item_type, *_ = get_args(evaled_type)
of_type = StrawberryAnnotation(
annotation=item_type,
Expand All @@ -194,7 +194,7 @@ def create_list(self, evaled_type: Any) -> StrawberryList:

return StrawberryList(of_type)

def create_optional(self, evaled_type: Any) -> StrawberryOptional:
def create_optional(self, evaled_type: type) -> StrawberryOptional:
types = get_args(evaled_type)
non_optional_types = tuple(
filter(
Expand All @@ -217,7 +217,7 @@ def create_optional(self, evaled_type: Any) -> StrawberryOptional:

return StrawberryOptional(of_type)

def create_type_var(self, evaled_type: TypeVar) -> StrawberryTypeVar:
def create_type_var(self, evaled_type: type) -> StrawberryTypeVar:
return StrawberryTypeVar(evaled_type)

def create_union(self, evaled_type: Type[Any], args: list[Any]) -> StrawberryUnion:
Expand Down Expand Up @@ -263,15 +263,15 @@ def _is_async_type(cls, annotation: type) -> bool:
return origin in ASYNC_TYPES

@classmethod
def _is_enum(cls, annotation: Any) -> bool:
def _is_enum(cls, annotation: type) -> bool:
# Type aliases are not types so we need to make sure annotation can go into
# issubclass
if not isinstance(annotation, type):
return False
return issubclass(annotation, Enum)

@classmethod
def _is_graphql_generic(cls, annotation: Any) -> bool:
def _is_graphql_generic(cls, annotation: type) -> bool:
if hasattr(annotation, "__origin__"):
if definition := get_object_definition(annotation.__origin__):
return definition.is_graphql_generic
Expand All @@ -281,11 +281,11 @@ def _is_graphql_generic(cls, annotation: Any) -> bool:
return False

@classmethod
def _is_lazy_type(cls, annotation: Any) -> bool:
def _is_lazy_type(cls, annotation: type) -> bool:
return isinstance(annotation, LazyType)

@classmethod
def _is_optional(cls, annotation: Any, args: List[Any]) -> bool:
def _is_optional(cls, annotation: type, args: List[type]) -> bool:
"""Returns True if the annotation is Optional[SomeType]"""

# Optionals are represented as unions
Expand All @@ -298,7 +298,7 @@ def _is_optional(cls, annotation: Any, args: List[Any]) -> bool:
return any(x is type(None) for x in types)

@classmethod
def _is_list(cls, annotation: Any) -> bool:
def _is_list(cls, annotation: type) -> bool:
"""Returns True if annotation is a List"""

annotation_origin = get_origin(annotation)
Expand All @@ -312,7 +312,7 @@ def _is_list(cls, annotation: Any) -> bool:
)

@classmethod
def _is_strawberry_type(cls, evaled_type: Any) -> bool:
def _is_strawberry_type(cls, evaled_type: TypeVar) -> bool:
# Prevent import cycles
from strawberry.union import StrawberryUnion

Expand All @@ -339,7 +339,7 @@ def _is_strawberry_type(cls, evaled_type: Any) -> bool:
return False

@classmethod
def _is_union(cls, annotation: Any, args: List[Any]) -> bool:
def _is_union(cls, annotation: type, args: List[type]) -> bool:
"""Returns True if annotation is a Union"""

# this check is needed because unions declared with the new syntax `A | B`
Expand All @@ -364,7 +364,7 @@ def _is_union(cls, annotation: Any, args: List[Any]) -> bool:
return any(isinstance(arg, StrawberryUnion) for arg in args)

@classmethod
def _strip_async_type(cls, annotation: Type[Any]) -> type:
def _strip_async_type(cls, annotation: Type) -> type:
return annotation.__args__[0]

@classmethod
Expand All @@ -377,7 +377,7 @@ def _strip_lazy_type(cls, annotation: LazyType[Any, Any]) -> type:
################################################################################


def _is_input_type(type_: Any) -> bool:
def _is_input_type(type_: TypeVar) -> bool:
if not has_object_definition(type_):
return False

Expand Down
6 changes: 3 additions & 3 deletions strawberry/auto.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import Any, Optional, Union, cast
from typing import Any, Dict, Optional, Union, cast
from typing_extensions import Annotated, get_args, get_origin

from strawberry.type import StrawberryType
Expand All @@ -24,11 +24,11 @@ class StrawberryAutoMeta(type):

"""

def __init__(self, *args: str, **kwargs: Any) -> None:
def __init__(self, *args: str, **kwargs: Dict[Any, Any]) -> None:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kwargs are implicitly marked as dicts 😊

Copy link
Contributor Author

@brunodantas brunodantas May 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm should we keep the Dict annotations? Ruff complained about the Any.

self._instance: Optional[StrawberryAuto] = None
super().__init__(*args, **kwargs)

def __call__(cls, *args: str, **kwargs: Any) -> Any:
def __call__(cls, *args: str, **kwargs: Dict[Any, Any]) -> StrawberryAuto:
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)

Expand Down
6 changes: 3 additions & 3 deletions strawberry/channels/handlers/ws_handler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import datetime
from typing import TYPE_CHECKING, Any, Optional, Sequence, Tuple, Union
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Tuple, Union

from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL

Expand Down Expand Up @@ -102,14 +102,14 @@ async def connect(self) -> None:
await self._handler.handle()
return None

async def receive(self, *args: str, **kwargs: Any) -> None:
async def receive(self, *args: str, **kwargs: Dict[Any, Any]) -> None:
# Overriding this so that we can pass the errors to handle_invalid_message
try:
await super().receive(*args, **kwargs)
except ValueError as e:
await self._handler.handle_invalid_message(str(e))

async def receive_json(self, content: Any, **kwargs: Any) -> None:
async def receive_json(self, content: Any, **kwargs: Dict[Any, Any]) -> None:
await self._handler.handle_message(content)

async def disconnect(self, code: int) -> None:
Expand Down
20 changes: 13 additions & 7 deletions strawberry/django/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Union,
Expand Down Expand Up @@ -139,7 +141,7 @@ def __init__(
graphql_ide: Optional[GraphQL_IDE] = "graphiql",
allow_queries_via_get: bool = True,
subscriptions_enabled: bool = False,
**kwargs: Any,
**kwargs: Dict[Any, Any],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider using Mapping instead of Dict for kwargs.

Using Mapping instead of Dict for **kwargs can provide more flexibility and better type safety, as Mapping is a more general type.

Suggested change
**kwargs: Dict[Any, Any],
**kwargs: Mapping[Any, Any],

) -> None:
self.schema = schema
self.allow_queries_via_get = allow_queries_via_get
Expand Down Expand Up @@ -198,15 +200,17 @@ class GraphQLView(
def get_root_value(self, request: HttpRequest) -> Optional[RootValue]:
return None

def get_context(self, request: HttpRequest, response: HttpResponse) -> Any:
def get_context(
self, request: HttpRequest, response: HttpResponse
) -> StrawberryDjangoContext:
return StrawberryDjangoContext(request=request, response=response)

def get_sub_response(self, request: HttpRequest) -> TemporalHttpResponse:
return TemporalHttpResponse()

@method_decorator(csrf_exempt)
def dispatch(
self, request: HttpRequest, *args: Any, **kwargs: Any
self, request: HttpRequest, *args: List[Any], **kwargs: Dict[Any, Any]
) -> Union[HttpResponseNotAllowed, TemplateResponse, HttpResponse]:
try:
return self.run(request=request)
Expand Down Expand Up @@ -245,7 +249,7 @@ class AsyncGraphQLView(
request_adapter_class = AsyncDjangoHTTPRequestAdapter

@classonlymethod # pyright: ignore[reportIncompatibleMethodOverride]
def as_view(cls, **initkwargs: Any) -> Callable[..., HttpResponse]:
def as_view(cls, **initkwargs: Dict[Any, Any]) -> Callable[..., HttpResponse]:
# This code tells django that this view is async, see docs here:
# https://docs.djangoproject.com/en/3.1/topics/async/#async-views

Expand All @@ -254,18 +258,20 @@ def as_view(cls, **initkwargs: Any) -> Callable[..., HttpResponse]:

return view

async def get_root_value(self, request: HttpRequest) -> Any:
async def get_root_value(self, request: HttpRequest) -> None:
return None

async def get_context(self, request: HttpRequest, response: HttpResponse) -> Any:
async def get_context(
self, request: HttpRequest, response: HttpResponse
) -> StrawberryDjangoContext:
return StrawberryDjangoContext(request=request, response=response)

async def get_sub_response(self, request: HttpRequest) -> TemporalHttpResponse:
return TemporalHttpResponse()

@method_decorator(csrf_exempt)
async def dispatch( # pyright: ignore
self, request: HttpRequest, *args: Any, **kwargs: Any
self, request: HttpRequest, *args: List[Any], **kwargs: Dict[Any, Any]
) -> Union[HttpResponseNotAllowed, TemplateResponse, HttpResponse]:
try:
return await self.run(request=request)
Expand Down
2 changes: 1 addition & 1 deletion strawberry/ext/mypy_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def lazy_type_analyze_callback(ctx: AnalyzeTypeContext) -> Type:
return type_


def _get_named_type(name: str, api: SemanticAnalyzerPluginInterface) -> Any:
def _get_named_type(name: str, api: SemanticAnalyzerPluginInterface) -> Instance | None:
if "." in name:
return api.named_type_or_none(name)

Expand Down
20 changes: 16 additions & 4 deletions strawberry/extensions/field_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import itertools
from functools import cached_property
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Union
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Union

if TYPE_CHECKING:
from typing_extensions import TypeAlias
Expand All @@ -20,14 +20,22 @@ def apply(self, field: StrawberryField) -> None: # pragma: no cover
pass

def resolve(
self, next_: SyncExtensionResolver, source: Any, info: Info, **kwargs: Any
self,
next_: SyncExtensionResolver,
source: Any,
info: Info,
**kwargs: Dict[Any, Any],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider using Mapping instead of Dict for kwargs.

Using Mapping instead of Dict for **kwargs can provide more flexibility and better type safety, as Mapping is a more general type.

Suggested change
**kwargs: Dict[Any, Any],
**kwargs: Mapping[Any, Any],

) -> Any: # pragma: no cover
raise NotImplementedError(
"Sync Resolve is not supported for this Field Extension"
)

async def resolve_async(
self, next_: AsyncExtensionResolver, source: Any, info: Info, **kwargs: Any
self,
next_: AsyncExtensionResolver,
source: Any,
info: Info,
**kwargs: Dict[Any, Any],
) -> Any: # pragma: no cover
raise NotImplementedError(
"Async Resolve is not supported for this Field Extension"
Expand All @@ -47,7 +55,11 @@ class SyncToAsyncExtension(FieldExtension):
Applied automatically"""

async def resolve_async(
self, next_: AsyncExtensionResolver, source: Any, info: Info, **kwargs: Any
self,
next_: AsyncExtensionResolver,
source: Any,
info: Info,
**kwargs: Dict[Any, Any],
) -> Any:
return next_(source, info, **kwargs)

Expand Down
9 changes: 4 additions & 5 deletions strawberry/type.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
List,
Mapping,
Expand Down Expand Up @@ -190,7 +189,7 @@ class WithStrawberryObjectDefinition(Protocol):


def has_object_definition(
obj: Any,
obj: type,
) -> TypeGuard[Type[WithStrawberryObjectDefinition]]:
if hasattr(obj, "__strawberry_definition__"):
return True
Expand All @@ -207,22 +206,22 @@ def has_object_definition(

@overload
def get_object_definition(
obj: Any,
obj: object,
*,
strict: Literal[True],
) -> StrawberryObjectDefinition: ...


@overload
def get_object_definition(
obj: Any,
obj: object,
*,
strict: bool = False,
) -> Optional[StrawberryObjectDefinition]: ...


def get_object_definition(
obj: Any,
obj: object,
*,
strict: bool = False,
) -> Optional[StrawberryObjectDefinition]:
Expand Down
2 changes: 1 addition & 1 deletion strawberry/types/fields/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def __init__(
"""

# TODO: Use this when doing the actual resolving? How to deal with async resolvers?
def __call__(self, *args: str, **kwargs: Any) -> T:
def __call__(self, *args: str, **kwargs: Dict) -> T:
if not callable(self.wrapped_func):
raise UncallableResolverError(self)
return self.wrapped_func(*args, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion strawberry/types/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
Selection = Union["SelectedField", "FragmentSpread", "InlineFragment"]


def convert_value(info: GraphQLResolveInfo, node: GQLValueNode) -> Any:
def convert_value(info: GraphQLResolveInfo, node: GQLValueNode) -> object:
"""Return useful value from any node."""
if isinstance(node, GQLVariableNode):
# Look up variable
Expand Down
Loading
Loading