Skip to content

Commit b990afc

Browse files
chore(typing): enable ruff ANN2, add more typehints from pyrefly infer (#1329)
Signed-off-by: arielle <[email protected]> Co-authored-by: vi <[email protected]>
1 parent bb0fcf5 commit b990afc

Some content is hidden

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

54 files changed

+398
-308
lines changed

changelog/1329.misc.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add more typing to most modules, increasing type completeness.

disnake/__main__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
import platform
66
import sys
77
from pathlib import Path
8-
from typing import Union
8+
from typing import List, Tuple, Union
99

1010
import aiohttp
1111

1212
import disnake
1313

1414

1515
def show_version() -> None:
16-
entries = []
16+
entries: List[str] = []
1717

1818
sys_ver = sys.version_info
1919
entries.append(
@@ -232,7 +232,7 @@ async def cog_after_user_command_invoke(self, inter):
232232
_translation_table = str.maketrans(_base_table)
233233

234234

235-
def to_path(parser, name: Union[str, Path], *, replace_spaces: bool = False):
235+
def to_path(parser, name: Union[str, Path], *, replace_spaces: bool = False) -> Path:
236236
if isinstance(name, Path):
237237
return name
238238

@@ -399,7 +399,7 @@ def add_newcog_args(subparser) -> None:
399399
parser.add_argument("--full", help="add all special methods as well", action="store_true")
400400

401401

402-
def parse_args():
402+
def parse_args() -> Tuple[argparse.ArgumentParser, argparse.Namespace]:
403403
parser = argparse.ArgumentParser(prog="disnake", description="Tools for helping with disnake")
404404
parser.add_argument("-v", "--version", action="store_true", help="shows the library version")
405405
parser.set_defaults(func=core)

disnake/abc.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@
8383
OverwriteType,
8484
PermissionOverwrite as PermissionOverwritePayload,
8585
)
86+
from .types.guild import ChannelPositionUpdate as ChannelPositionUpdatePayload
8687
from .types.threads import PartialForumTag as PartialForumTagPayload
8788
from .ui._types import MessageComponents
8889
from .ui.view import View
@@ -312,9 +313,9 @@ async def _move(
312313
# add ourselves at our designated position
313314
channels.insert(index, self)
314315

315-
payload = []
316+
payload: List[ChannelPositionUpdatePayload] = []
316317
for index, c in enumerate(channels):
317-
d: Dict[str, Any] = {"id": c.id, "position": index}
318+
d: ChannelPositionUpdatePayload = {"id": c.id, "position": index}
318319
if parent_id is not MISSING and c.id == self.id:
319320
d.update(parent_id=parent_id, lock_permissions=lock_permissions)
320321
payload.append(d)
@@ -508,7 +509,7 @@ def changed_roles(self) -> List[Role]:
508509
"""List[:class:`.Role`]: Returns a list of roles that have been overridden from
509510
their default values in the :attr:`.Guild.roles` attribute.
510511
"""
511-
ret = []
512+
ret: List[Role] = []
512513
g = self.guild
513514
for overwrite in filter(lambda o: o.is_role(), self._overwrites):
514515
role = g.get_role(overwrite.id)
@@ -1272,11 +1273,11 @@ async def move(self, **kwargs: Any) -> None:
12721273
raise ValueError("Could not resolve appropriate move position")
12731274

12741275
channels.insert(max((index + offset), 0), self)
1275-
payload = []
1276+
payload: List[ChannelPositionUpdatePayload] = []
12761277
lock_permissions = kwargs.get("sync_permissions", False)
12771278
reason = kwargs.get("reason")
12781279
for index, channel in enumerate(channels):
1279-
d = {"id": channel.id, "position": index}
1280+
d: ChannelPositionUpdatePayload = {"id": channel.id, "position": index}
12801281
if parent_id is not MISSING and channel.id == self.id:
12811282
d.update(parent_id=parent_id, lock_permissions=lock_permissions)
12821283
payload.append(d)

disnake/activity.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,7 @@ def __repr__(self) -> str:
607607
return f"<Streaming name={self.name!r}>"
608608

609609
@property
610-
def twitch_name(self):
610+
def twitch_name(self) -> Optional[str]:
611611
"""Optional[:class:`str`]: If provided, the twitch name of the user streaming.
612612
613613
This corresponds to the ``large_image`` key of the :attr:`Streaming.assets`

disnake/app_commands.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1250,7 +1250,7 @@ def __init__(self, *, data: ApplicationCommandPermissionsPayload, guild_id: int)
12501250
def __repr__(self) -> str:
12511251
return f"<ApplicationCommandPermissions id={self.id!r} type={self.type!r} permission={self.permission!r}>"
12521252

1253-
def __eq__(self, other):
1253+
def __eq__(self, other) -> bool:
12541254
return (
12551255
self.id == other.id and self.type == other.type and self.permission == other.permission
12561256
)

disnake/audit_logs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,8 @@ def _transform_guild_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Opti
118118

119119
def _transform_overwrites(
120120
entry: AuditLogEntry, data: List[PermissionOverwritePayload]
121-
) -> List[Tuple[Object, PermissionOverwrite]]:
122-
overwrites = []
121+
) -> List[Tuple[Union[Object, Member, Role, User], PermissionOverwrite]]:
122+
overwrites: List[Tuple[Union[Object, Member, Role, User], PermissionOverwrite]] = []
123123
for elem in data:
124124
allow = Permissions(int(elem["allow"]))
125125
deny = Permissions(int(elem["deny"]))

disnake/channel.py

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def _update(self, guild: Guild, data: TextChannelPayload) -> None:
306306
)
307307
self._fill_overwrites(data)
308308

309-
async def _get_channel(self):
309+
async def _get_channel(self) -> Self:
310310
return self
311311

312312
@property
@@ -1227,7 +1227,7 @@ def members(self) -> List[Member]:
12271227
if isinstance(self.guild, Object):
12281228
return []
12291229

1230-
ret = []
1230+
ret: List[Member] = []
12311231
for user_id, state in self.guild._voice_states.items():
12321232
if state.channel and state.channel.id == self.id:
12331233
member = self.guild.get_member(user_id)
@@ -1392,7 +1392,7 @@ def _update(self, guild: Guild, data: VoiceChannelPayload) -> None:
13921392
self.slowmode_delay: int = data.get("rate_limit_per_user", 0)
13931393
self.last_message_id: Optional[int] = utils._get_as_snowflake(data, "last_message_id")
13941394

1395-
async def _get_channel(self):
1395+
async def _get_channel(self: Self) -> Self:
13961396
return self
13971397

13981398
@property
@@ -2079,7 +2079,7 @@ def _update(self, guild: Guild, data: StageChannelPayload) -> None:
20792079
self.slowmode_delay: int = data.get("rate_limit_per_user", 0)
20802080
self.last_message_id: Optional[int] = utils._get_as_snowflake(data, "last_message_id")
20812081

2082-
async def _get_channel(self):
2082+
async def _get_channel(self) -> Self:
20832083
return self
20842084

20852085
@property
@@ -3108,7 +3108,7 @@ def channels(self) -> List[GuildChannelType]:
31083108
if isinstance(self.guild, Object):
31093109
return []
31103110

3111-
def comparator(channel):
3111+
def comparator(channel: GuildChannelType) -> Tuple[bool, int]:
31123112
return (
31133113
not isinstance(channel, (TextChannel, ThreadOnlyGuildChannel)),
31143114
channel.position,
@@ -4789,7 +4789,7 @@ def __init__(self, *, me: ClientUser, state: ConnectionState, data: DMChannelPay
47894789
)
47904790
self._flags: int = data.get("flags", 0)
47914791

4792-
async def _get_channel(self):
4792+
async def _get_channel(self) -> Self:
47934793
return self
47944794

47954795
def __str__(self) -> str:
@@ -4962,7 +4962,7 @@ def _update_group(self, data: GroupChannelPayload) -> None:
49624962
else:
49634963
self.owner = utils.find(lambda u: u.id == self.owner_id, self.recipients)
49644964

4965-
async def _get_channel(self):
4965+
async def _get_channel(self) -> Self:
49664966
return self
49674967

49684968
def __str__(self) -> str:
@@ -5133,7 +5133,9 @@ def get_partial_message(self, message_id: int, /) -> PartialMessage:
51335133
return PartialMessage(channel=self, id=message_id)
51345134

51355135

5136-
def _guild_channel_factory(channel_type: int):
5136+
def _guild_channel_factory(
5137+
channel_type: int,
5138+
) -> Tuple[Optional[Type[GuildChannelType]], ChannelType]:
51375139
value = try_enum(ChannelType, channel_type)
51385140
if value is ChannelType.text:
51395141
return TextChannel, value
@@ -5153,7 +5155,11 @@ def _guild_channel_factory(channel_type: int):
51535155
return None, value
51545156

51555157

5156-
def _channel_factory(channel_type: int):
5158+
def _channel_factory(
5159+
channel_type: int,
5160+
) -> Tuple[
5161+
Optional[Union[Type[GuildChannelType], Type[DMChannel], Type[GroupChannel]]], ChannelType
5162+
]:
51575163
cls, value = _guild_channel_factory(channel_type)
51585164
if value is ChannelType.private:
51595165
return DMChannel, value
@@ -5163,14 +5169,21 @@ def _channel_factory(channel_type: int):
51635169
return cls, value
51645170

51655171

5166-
def _threaded_channel_factory(channel_type: int):
5172+
def _threaded_channel_factory(
5173+
channel_type: int,
5174+
) -> Tuple[
5175+
Optional[Union[Type[GuildChannelType], Type[DMChannel], Type[GroupChannel], Type[Thread]]],
5176+
ChannelType,
5177+
]:
51675178
cls, value = _channel_factory(channel_type)
51685179
if value in (ChannelType.private_thread, ChannelType.public_thread, ChannelType.news_thread):
51695180
return Thread, value
51705181
return cls, value
51715182

51725183

5173-
def _threaded_guild_channel_factory(channel_type: int):
5184+
def _threaded_guild_channel_factory(
5185+
channel_type: int,
5186+
) -> Tuple[Optional[Union[Type[GuildChannelType], Type[Thread]]], ChannelType]:
51745187
cls, value = _guild_channel_factory(channel_type)
51755188
if value in (ChannelType.private_thread, ChannelType.public_thread, ChannelType.news_thread):
51765189
return Thread, value

disnake/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1347,7 +1347,7 @@ def activity(self, value: Optional[ActivityTypes]) -> None:
13471347
raise TypeError("activity must derive from BaseActivity.")
13481348

13491349
@property
1350-
def status(self):
1350+
def status(self) -> Status:
13511351
""":class:`.Status`: The status being used upon logging on to Discord.
13521352
13531353
.. versionadded:: 2.0

disnake/embeds.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -834,7 +834,7 @@ def to_dict(self) -> EmbedData:
834834
return result
835835

836836
@classmethod
837-
def set_default_colour(cls, value: Optional[Union[int, Colour]]):
837+
def set_default_colour(cls, value: Optional[Union[int, Colour]]) -> Optional[Colour]:
838838
"""Set the default colour of all new embeds.
839839
840840
.. versionadded:: 2.4

disnake/enums.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@
8181
"NameplatePalette",
8282
)
8383

84+
EnumMetaT = TypeVar("EnumMetaT", bound="Type[EnumMeta]")
85+
8486

8587
class _EnumValueBase(NamedTuple):
8688
if TYPE_CHECKING:
@@ -110,7 +112,7 @@ def _create_value_cls(name: str, comparable: bool) -> Type[_EnumValueBase]:
110112
return type(f"{parent.__name__}_{name}", (parent,), {"_cls_name": name}) # type: ignore
111113

112114

113-
def _is_descriptor(obj):
115+
def _is_descriptor(obj) -> bool:
114116
return hasattr(obj, "__get__") or hasattr(obj, "__set__") or hasattr(obj, "__delete__")
115117

116118

@@ -122,7 +124,7 @@ class EnumMeta(type):
122124
_enum_value_map_: ClassVar[Dict[Any, Any]]
123125
_enum_value_cls_: ClassVar[Type[_EnumValueBase]]
124126

125-
def __new__(cls, name: str, bases, attrs, *, comparable: bool = False):
127+
def __new__(cls: EnumMetaT, name: str, bases, attrs, *, comparable: bool = False) -> EnumMetaT:
126128
value_mapping = {}
127129
member_mapping = {}
128130
member_names = []
@@ -176,16 +178,16 @@ def __repr__(cls) -> str:
176178
def __members__(cls):
177179
return types.MappingProxyType(cls._enum_member_map_)
178180

179-
def __call__(cls, value):
181+
def __call__(cls, value: Any) -> Any:
180182
try:
181183
return cls._enum_value_map_[value]
182184
except (KeyError, TypeError):
183185
raise ValueError(f"{value!r} is not a valid {cls.__name__}") from None
184186

185-
def __getitem__(cls, key):
187+
def __getitem__(cls, key: str) -> Any:
186188
return cls._enum_member_map_[key]
187189

188-
def __setattr__(cls, name: str, value) -> NoReturn:
190+
def __setattr__(cls, name: str, value: Any) -> NoReturn:
189191
raise TypeError("Enums are immutable.")
190192

191193
def __delattr__(cls, attr) -> NoReturn:
@@ -206,7 +208,7 @@ def __instancecheck__(self, instance) -> bool:
206208

207209
class Enum(metaclass=EnumMeta):
208210
@classmethod
209-
def try_value(cls, value):
211+
def try_value(cls, value: Any) -> Self:
210212
try:
211213
return cls._enum_value_map_[value]
212214
except (KeyError, TypeError):

0 commit comments

Comments
 (0)