Skip to content

Commit c3e7453

Browse files
authored
feat: 🚨 upgrade ruff config (#107)
1 parent d31505c commit c3e7453

Some content is hidden

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

77 files changed

+352
-370
lines changed

discord/__version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@
3535

3636
from typing import Literal, NamedTuple
3737

38-
from .utils.private import deprecated
3938
from ._version import __version__, __version_tuple__
39+
from .utils.private import deprecated
4040

4141

4242
class AdvancedVersionInfo(TypedDict):

discord/abc.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@
4141
runtime_checkable,
4242
)
4343

44-
from .utils.private import warn_deprecated
4544
from . import utils
4645
from .context_managers import Typing
4746
from .enums import ChannelType
@@ -56,6 +55,7 @@
5655
from .role import Role
5756
from .scheduled_events import ScheduledEvent
5857
from .sticker import GuildSticker, StickerItem
58+
from .utils.private import warn_deprecated
5959
from .voice_client import VoiceClient, VoiceProtocol
6060

6161
__all__ = (
@@ -99,9 +99,9 @@
9999
from .ui.view import View
100100
from .user import ClientUser
101101

102-
PartialMessageableChannel = Union[TextChannel, VoiceChannel, StageChannel, Thread, DMChannel, PartialMessageable]
103-
MessageableChannel = Union[PartialMessageableChannel, GroupChannel]
104-
SnowflakeTime = Union["Snowflake", datetime]
102+
PartialMessageableChannel = TextChannel | VoiceChannel | StageChannel | Thread | DMChannel | PartialMessageable
103+
MessageableChannel = PartialMessageableChannel | GroupChannel
104+
SnowflakeTime = "Snowflake" | datetime
105105

106106
MISSING = utils.MISSING
107107

@@ -912,8 +912,8 @@ async def set_permissions(self, target, *, overwrite=MISSING, reason=None, **per
912912
raise InvalidArgument("No overwrite provided.")
913913
try:
914914
overwrite = PermissionOverwrite(**permissions)
915-
except (ValueError, TypeError):
916-
raise InvalidArgument("Invalid permissions given to keyword arguments.")
915+
except (ValueError, TypeError) as e:
916+
raise InvalidArgument("Invalid permissions given to keyword arguments.") from e
917917
elif len(permissions) > 0:
918918
raise InvalidArgument("Cannot mix overwrite and keyword arguments.")
919919

@@ -1753,8 +1753,8 @@ def can_send(self, *objects) -> bool:
17531753
if obj.guild_id == channel.guild.id:
17541754
continue
17551755

1756-
except (KeyError, AttributeError):
1757-
raise TypeError(f"The object {obj} is of an invalid type.")
1756+
except (KeyError, AttributeError) as e:
1757+
raise TypeError(f"The object {obj} is of an invalid type.") from e
17581758

17591759
if not getattr(channel.permissions_for(channel.guild.me), permission):
17601760
return False

discord/activity.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -805,7 +805,7 @@ def __repr__(self) -> str:
805805
return f"<CustomActivity name={self.name!r} emoji={self.emoji!r}>"
806806

807807

808-
ActivityTypes = Union[Activity, Game, CustomActivity, Streaming, Spotify]
808+
ActivityTypes = Activity | Game | CustomActivity | Streaming | Spotify
809809

810810

811811
@overload

discord/appinfo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@
2727

2828
from typing import TYPE_CHECKING
2929

30-
from .utils.private import warn_deprecated, get_as_snowflake
3130
from . import utils
3231
from .asset import Asset
3332
from .permissions import Permissions
33+
from .utils.private import get_as_snowflake, warn_deprecated
3434

3535
if TYPE_CHECKING:
3636
from .guild import Guild

discord/audit_logs.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,9 @@
2525

2626
from __future__ import annotations
2727

28-
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generator, TypeVar
2928
from functools import cached_property
29+
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generator, TypeVar
3030

31-
from .utils.private import get_as_snowflake
3231
from . import enums, utils
3332
from .asset import Asset
3433
from .automod import AutoModAction, AutoModTriggerMetadata
@@ -37,6 +36,7 @@
3736
from .mixins import Hashable
3837
from .object import Object
3938
from .permissions import PermissionOverwrite, Permissions
39+
from .utils.private import get_as_snowflake
4040

4141
__all__ = (
4242
"AuditLogDiff",
@@ -383,7 +383,7 @@ def _handle_role(
383383
elem: list[RolePayload],
384384
) -> None:
385385
if not hasattr(first, "roles"):
386-
setattr(first, "roles", [])
386+
first.roles = []
387387

388388
data = []
389389
g: Guild = entry.guild # type: ignore
@@ -398,7 +398,7 @@ def _handle_role(
398398

399399
data.append(role)
400400

401-
setattr(second, "roles", data)
401+
second.roles = data
402402

403403
def _handle_trigger_metadata(
404404
self,
@@ -409,13 +409,13 @@ def _handle_trigger_metadata(
409409
attr: str,
410410
) -> None:
411411
if not hasattr(first, "trigger_metadata"):
412-
setattr(first, "trigger_metadata", None)
412+
first.trigger_metadata = None
413413

414414
key = attr.split("_", 1)[-1]
415415
data = {key: elem}
416416
tm = AutoModTriggerMetadata.from_dict(data)
417417

418-
setattr(second, "trigger_metadata", tm)
418+
second.trigger_metadata = tm
419419

420420

421421
class _AuditLogProxyMemberPrune:

discord/banners.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,12 @@
1111
import time
1212
import warnings
1313
from typing import Sequence
14-
from . import __version__
1514

1615
import colorlog
1716
import colorlog.escape_codes
1817

18+
from . import __version__
19+
1920
__all__: Sequence[str] = ("start_logging", "print_banner")
2021

2122

discord/bot.py

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def pending_application_commands(self):
111111
def commands(self) -> list[ApplicationCommand | Any]:
112112
commands = self.application_commands
113113
if self._bot._supports_prefixed_commands and hasattr(self._bot, "prefixed_commands"):
114-
commands += getattr(self._bot, "prefixed_commands")
114+
commands += self._bot.prefixed_commands
115115
return commands
116116

117117
@property
@@ -265,7 +265,7 @@ def _check_command(cmd: ApplicationCommand, match: Mapping[str, Any]) -> bool:
265265
if isinstance(cmd, SlashCommandGroup):
266266
if len(cmd.subcommands) != len(match.get("options", [])):
267267
return True
268-
for i, subcommand in enumerate(cmd.subcommands):
268+
for subcommand in cmd.subcommands:
269269
match_ = next(
270270
(data for data in match["options"] if data["name"] == subcommand.name),
271271
MISSING,
@@ -357,8 +357,9 @@ def _check_command(cmd: ApplicationCommand, match: Mapping[str, Any]) -> bool:
357357
return_value.append({"command": cmd, "action": None, "id": int(match["id"])})
358358

359359
# Now let's see if there are any commands on discord that we need to delete
360-
for cmd, value_ in registered_commands_dict.items():
361-
match = find(lambda c: c.name == value_["name"], pending)
360+
for _, value_ in registered_commands_dict.items():
361+
# name default arg is used because loop variables leak in surrounding scope
362+
match = find(lambda c, name=value_["name"]: c.name == name, pending)
362363
if match is None:
363364
# We have this command registered but not in our list
364365
return_value.append(
@@ -517,7 +518,11 @@ def register(
517518
)
518519
continue
519520
# We can assume the command item is a command, since it's only a string if action is delete
520-
match = find(lambda c: c.name == cmd["command"].name and c.type == cmd["command"].type, pending)
521+
wanted = cmd["command"]
522+
name = wanted.name
523+
type_ = wanted.type
524+
525+
match = next((c for c in pending if c.name == name and c.type == type_), None)
521526
if match is None:
522527
continue
523528
if cmd["action"] == "edit":
@@ -606,8 +611,10 @@ def register(
606611
registered = await register("bulk", data, guild_id=guild_id)
607612

608613
for i in registered:
614+
type_ = i.get("type")
615+
# name, type_ default args are used because loop variables leak in surrounding scope
609616
cmd = find(
610-
lambda c: c.name == i["name"] and c.type == i.get("type"),
617+
lambda c, name=i["name"], type_=type_: c.name == name and c.type == type_,
611618
self.pending_application_commands,
612619
)
613620
if not cmd:
@@ -624,7 +631,7 @@ async def sync_commands(
624631
force: bool = False,
625632
guild_ids: list[int] | None = None,
626633
register_guild_commands: bool = True,
627-
check_guilds: list[int] | None = [],
634+
check_guilds: list[int] | None = None,
628635
delete_existing: bool = True,
629636
) -> None:
630637
"""|coro|
@@ -711,25 +718,37 @@ async def on_connect():
711718
)
712719
registered_guild_commands[guild_id] = app_cmds
713720

714-
for i in registered_commands:
721+
for item in registered_commands:
722+
type_ = item.get("type")
723+
# name, type_ default args are used because loop variables leak in surrounding scope
715724
cmd = find(
716-
lambda c: c.name == i["name"] and c.guild_ids is None and c.type == i.get("type"),
725+
lambda c, name=item["name"], type_=type_: (c.name == name and c.guild_ids is None and c.type == type_),
717726
self.pending_application_commands,
718727
)
719728
if cmd:
720-
cmd.id = i["id"]
729+
cmd.id = item["id"]
721730
self._application_commands[cmd.id] = cmd
722731

723732
if register_guild_commands and registered_guild_commands:
724733
for guild_id, guild_cmds in registered_guild_commands.items():
725734
for i in guild_cmds:
726-
cmd = find(
727-
lambda cmd: cmd.name == i["name"]
728-
and cmd.type == i.get("type")
729-
and cmd.guild_ids is not None
730-
and (guild_id := i.get("guild_id"))
731-
and guild_id in cmd.guild_ids,
732-
self.pending_application_commands,
735+
name = i["name"]
736+
type_ = i.get("type")
737+
target_gid = i.get("guild_id")
738+
if target_gid is None:
739+
continue
740+
741+
cmd = next(
742+
(
743+
c
744+
for c in self.pending_application_commands
745+
if c.name == name
746+
and c.type == type_
747+
and c.guild_ids is not None
748+
and target_gid == guild_id
749+
and target_gid in c.guild_ids
750+
),
751+
None,
733752
)
734753
if not cmd:
735754
# command has not been added yet

discord/channel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939

4040
import discord.abc
4141

42-
from .utils.private import bytes_to_base64_data, get_as_snowflake, copy_doc
4342
from . import utils
4443
from .asset import Asset
4544
from .emoji import GuildEmoji
@@ -65,6 +64,7 @@
6564
from .stage_instance import StageInstance
6665
from .threads import Thread
6766
from .utils import MISSING
67+
from .utils.private import bytes_to_base64_data, copy_doc, get_as_snowflake
6868

6969
__all__ = (
7070
"TextChannel",

discord/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
from discord.banners import print_banner, start_logging
3939

4040
from . import utils
41-
from .utils.private import resolve_invite, resolve_template, bytes_to_base64_data, SequenceProxy
4241
from .activity import ActivityTypes, BaseActivity, create_activity
4342
from .appinfo import AppInfo, PartialAppInfo
4443
from .application_role_connection import ApplicationRoleConnectionMetadata
@@ -64,6 +63,7 @@
6463
from .ui.view import View
6564
from .user import ClientUser, User
6665
from .utils import MISSING
66+
from .utils.private import SequenceProxy, bytes_to_base64_data, resolve_invite, resolve_template
6767
from .voice_client import VoiceClient
6868
from .webhook import Webhook
6969
from .widget import Widget

discord/cog.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,12 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
186186
commands[f"ext_{cmd.ext_variant.qualified_name}"] = cmd.ext_variant
187187

188188
if inspect.iscoroutinefunction(value):
189-
try:
190-
getattr(value, "__cog_listener__")
191-
except AttributeError:
192-
continue
193-
else:
189+
if hasattr(value, "__cog_listener__"):
194190
if elem.startswith(("cog_", "bot_")):
195191
raise TypeError(no_bot_cog.format(base, elem))
196192
listeners[elem] = value
193+
else:
194+
continue
197195

198196
new_cls.__cog_commands__ = list(commands.values())
199197

@@ -711,7 +709,7 @@ def _remove_module_references(self, name: str) -> None:
711709

712710
def _call_module_finalizers(self, lib: types.ModuleType, key: str) -> None:
713711
try:
714-
func = getattr(lib, "teardown")
712+
func = lib.teardown
715713
except AttributeError:
716714
pass
717715
else:
@@ -738,10 +736,10 @@ def _load_from_module_spec(self, spec: importlib.machinery.ModuleSpec, key: str)
738736
raise errors.ExtensionFailed(key, e) from e
739737

740738
try:
741-
setup = getattr(lib, "setup")
742-
except AttributeError:
739+
setup = lib.setup
740+
except AttributeError as e:
743741
del sys.modules[key]
744-
raise errors.NoEntryPointError(key)
742+
raise errors.NoEntryPointError(key) from e
745743

746744
try:
747745
setup(self)
@@ -756,8 +754,8 @@ def _load_from_module_spec(self, spec: importlib.machinery.ModuleSpec, key: str)
756754
def _resolve_name(self, name: str, package: str | None) -> str:
757755
try:
758756
return importlib.util.resolve_name(name, package)
759-
except ImportError:
760-
raise errors.ExtensionNotFound(name)
757+
except ImportError as e:
758+
raise errors.ExtensionNotFound(name) from e
761759

762760
@overload
763761
def load_extension(

0 commit comments

Comments
 (0)