Skip to content

refactor(lint): add flake8-return rules #948

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

Open
wants to merge 8 commits into
base: master
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
5 changes: 3 additions & 2 deletions disnake/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,7 @@ async def _edit(

if options:
return await self._state.http.edit_channel(self.id, reason=reason, **options)
return None

def _fill_overwrites(self, data: GuildChannelPayload) -> None:
self._overwrites = []
Expand Down Expand Up @@ -1633,7 +1634,7 @@ async def send(
if view is not None and components is not None:
raise TypeError("cannot pass both view and components parameter to send()")

elif view:
if view:
if not hasattr(view, "__discord_ui_view__"):
raise TypeError(f"view parameter must be View not {view.__class__!r}")

Expand All @@ -1655,7 +1656,7 @@ async def send(
if files is not None:
if len(files) > 10:
raise ValueError("files parameter must be a list of up to 10 elements")
elif not all(isinstance(file, File) for file in files):
if not all(isinstance(file, File) for file in files):
raise TypeError("files parameter must be a list of File")

try:
Expand Down
4 changes: 2 additions & 2 deletions disnake/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def created_at(self) -> Optional[datetime.datetime]:
return datetime.datetime.fromtimestamp(
self._created_at / 1000, tz=datetime.timezone.utc
)
return None

@property
def start(self) -> Optional[datetime.datetime]:
Expand Down Expand Up @@ -830,8 +831,7 @@ def __str__(self) -> str:
if self.name:
return f"{self.emoji} {self.name}"
return str(self.emoji)
else:
return str(self.name)
return str(self.name)

def __repr__(self) -> str:
return f"<CustomActivity name={self.name!r} emoji={self.emoji!r}>"
Expand Down
5 changes: 2 additions & 3 deletions disnake/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,8 @@ async def save(
if seek_begin:
fp.seek(0)
return written
else:
with open(fp, "wb") as f:
return f.write(data)
with open(fp, "wb") as f:
return f.write(data)

async def to_file(
self,
Expand Down
9 changes: 4 additions & 5 deletions disnake/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,13 +231,12 @@ def _transform_type(
action_name = entry.action.name
if action_name.startswith("sticker_"):
return enums.try_enum(enums.StickerType, data)
elif action_name.startswith("webhook_"):
if action_name.startswith("webhook_"):
return enums.try_enum(enums.WebhookType, data)
elif action_name.startswith("integration_") or action_name.startswith("overwrite_"):
if action_name.startswith("integration_") or action_name.startswith("overwrite_"):
# integration: str, overwrite: int
return data
else:
return enums.try_enum(enums.ChannelType, data)
return enums.try_enum(enums.ChannelType, data)


def _transform_datetime(entry: AuditLogEntry, data: Optional[str]) -> Optional[datetime.datetime]:
Expand Down Expand Up @@ -378,7 +377,7 @@ def __init__(self, entry: AuditLogEntry, data: List[AuditLogChangePayload]) -> N
if attr == "$add":
self._handle_role(self.before, self.after, entry, elem["new_value"]) # type: ignore
continue
elif attr == "$remove":
if attr == "$remove":
self._handle_role(self.after, self.before, entry, elem["new_value"]) # type: ignore
continue

Expand Down
30 changes: 19 additions & 11 deletions disnake/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,8 @@ async def edit(
# the payload will always be the proper channel payload
return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore

return None

Comment on lines 477 to +481
Copy link
Member

Choose a reason for hiding this comment

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

nit: the spacing here seems weird, whitespace above the if would make more sense, i.e.

            **kwargs,
        )

        if payload is not None:
            # the payload will always be the proper channel payload
            return self.__class__(state=self._state, guild=self.guild, data=payload)  # type: ignore
        return None

@utils.copy_doc(disnake.abc.GuildChannel.clone)
async def clone(
self, *, name: Optional[str] = None, reason: Optional[str] = None
Expand Down Expand Up @@ -1447,6 +1449,8 @@ async def edit(
# the payload will always be the proper channel payload
return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore

return None

async def delete_messages(self, messages: Iterable[Snowflake]) -> None:
"""|coro|

Expand Down Expand Up @@ -2196,6 +2200,8 @@ async def edit(
# the payload will always be the proper channel payload
return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore

return None

async def delete_messages(self, messages: Iterable[Snowflake]) -> None:
"""|coro|

Expand Down Expand Up @@ -2626,6 +2632,8 @@ async def edit(
# the payload will always be the proper channel payload
return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore

return None

@overload
async def move(
self,
Expand Down Expand Up @@ -3298,6 +3306,8 @@ async def edit(
# the payload will always be the proper channel payload
return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore

return None

@utils.copy_doc(disnake.abc.GuildChannel.clone)
async def clone(
self, *, name: Optional[str] = None, reason: Optional[str] = None
Expand Down Expand Up @@ -3554,7 +3564,7 @@ async def create_thread(

if params.files and len(params.files) > 10:
raise ValueError("files parameter must be a list of up to 10 elements")
elif params.files and not all(isinstance(file, File) for file in params.files):
if params.files and not all(isinstance(file, File) for file in params.files):
raise TypeError("files parameter must be a list of File")

channel_data = {
Expand Down Expand Up @@ -4112,28 +4122,26 @@ def _guild_channel_factory(channel_type: int):
value = try_enum(ChannelType, channel_type)
if value is ChannelType.text:
return TextChannel, value
elif value is ChannelType.voice:
if value is ChannelType.voice:
return VoiceChannel, value
elif value is ChannelType.category:
if value is ChannelType.category:
return CategoryChannel, value
elif value is ChannelType.news:
if value is ChannelType.news:
return TextChannel, value
elif value is ChannelType.stage_voice:
if value is ChannelType.stage_voice:
return StageChannel, value
elif value is ChannelType.forum:
if value is ChannelType.forum:
return ForumChannel, value
else:
return None, value
return None, value
Comment on lines 4122 to +4135
Copy link
Member

Choose a reason for hiding this comment

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

These should be lookup tables - out of scope here though



def _channel_factory(channel_type: int):
cls, value = _guild_channel_factory(channel_type)
if value is ChannelType.private:
return DMChannel, value
elif value is ChannelType.group:
if value is ChannelType.group:
return GroupChannel, value
else:
return cls, value
return cls, value


def _threaded_channel_factory(channel_type: int):
Expand Down
2 changes: 2 additions & 0 deletions disnake/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,7 @@ def stop_loop_on_completion(f) -> None:
except KeyboardInterrupt:
# I am unsure why this gets raised here but suppress it anyway
return None
return None

# properties

Expand Down Expand Up @@ -1261,6 +1262,7 @@ def get_stage_instance(self, id: int, /) -> Optional[StageInstance]:

if isinstance(channel, StageChannel):
return channel.instance
return None

def get_guild(self, id: int, /) -> Optional[Guild]:
"""Returns a guild with the given ID.
Expand Down
21 changes: 10 additions & 11 deletions disnake/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,21 +684,20 @@ def _component_factory(data: ComponentPayload, *, type: Type[C] = Component) ->
component_type = data["type"]
if component_type == 1:
return ActionRow(data) # type: ignore
elif component_type == 2:
if component_type == 2:
return Button(data) # type: ignore
elif component_type == 3:
if component_type == 3:
return StringSelectMenu(data) # type: ignore
elif component_type == 4:
if component_type == 4:
return TextInput(data) # type: ignore
elif component_type == 5:
if component_type == 5:
return UserSelectMenu(data) # type: ignore
elif component_type == 6:
if component_type == 6:
return RoleSelectMenu(data) # type: ignore
elif component_type == 7:
if component_type == 7:
return MentionableSelectMenu(data) # type: ignore
elif component_type == 8:
if component_type == 8:
return ChannelSelectMenu(data) # type: ignore
else:
assert_never(component_type)
as_enum = try_enum(ComponentType, component_type)
return Component._raw_construct(type=as_enum) # type: ignore
assert_never(component_type)
as_enum = try_enum(ComponentType, component_type)
return Component._raw_construct(type=as_enum) # type: ignore
5 changes: 2 additions & 3 deletions disnake/embeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,9 +830,8 @@ def _handle_resource(self, url: Optional[Any], file: File, *, key: _FileKey) ->
raise TypeError("File must have a filename")
self._files[key] = file
return f"attachment://{file.filename}"
else:
self._files.pop(key, None)
return str(url) if url is not None else None
self._files.pop(key, None)
return str(url) if url is not None else None

def check_limits(self) -> None:
"""Checks if this embed fits within the limits dictated by Discord.
Expand Down
39 changes: 19 additions & 20 deletions disnake/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,44 +461,43 @@ def target_type(self) -> Optional[str]:
v = self.value
if v == -1:
return "all"
elif v < 10:
if v < 10:
return "guild"
elif v < 20:
if v < 20:
return "channel"
elif v < 30:
if v < 30:
return "user"
elif v < 40:
if v < 40:
return "role"
elif v < 50:
if v < 50:
return "invite"
elif v < 60:
if v < 60:
return "webhook"
elif v < 70:
if v < 70:
return "emoji"
elif v == 73:
if v == 73:
return "channel"
elif v < 80:
if v < 80:
return "message"
elif v < 83:
if v < 83:
return "integration"
elif v < 90:
if v < 90:
return "stage_instance"
elif v < 93:
if v < 93:
return "sticker"
elif v < 103:
if v < 103:
return "guild_scheduled_event"
elif v < 113:
if v < 113:
return "thread"
elif v < 122:
if v < 122:
return "application_command_or_integration"
elif v < 140:
if v < 140:
return None
elif v < 143:
if v < 143:
return "automod_rule"
elif v < 146:
if v < 146:
return "user"
else:
return None
return None


class UserFlags(Enum):
Expand Down
21 changes: 9 additions & 12 deletions disnake/ext/commands/base_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async def wrapped(*args, **kwargs):
except CommandError:
raise
except asyncio.CancelledError:
return
return None
except Exception as exc:
raise CommandInvokeError(exc) from exc
return ret
Expand Down Expand Up @@ -220,13 +220,12 @@ def copy(self: AppCommandT) -> AppCommandT:
return self._ensure_assignment_on_copy(copy)

def _update_copy(self: AppCommandT, kwargs: Dict[str, Any]) -> AppCommandT:
if kwargs:
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = type(self)(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)
else:
if not kwargs:
return self.copy()
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = type(self)(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)

@property
def dm_permission(self) -> bool:
Expand Down Expand Up @@ -295,8 +294,7 @@ async def __call__(self, interaction: ApplicationCommandInteraction, *args, **kw
"""
if self.cog is not None:
return await self.callback(self.cog, interaction, *args, **kwargs)
else:
return await self.callback(interaction, *args, **kwargs)
return await self.callback(interaction, *args, **kwargs)

def _prepare_cooldowns(self, inter: ApplicationCommandInteraction) -> None:
if self._buckets.valid:
Expand Down Expand Up @@ -430,13 +428,12 @@ async def _call_local_error_handler(
self, inter: ApplicationCommandInteraction, error: CommandError
) -> Any:
if not self.has_error_handler():
return
return None

injected = wrap_callback(self.on_error)
if self.cog is not None:
return await injected(self.cog, inter, error)
else:
return await injected(inter, error)
return await injected(inter, error)

async def _call_external_error_handlers(
self, inter: ApplicationCommandInteraction, error: CommandError
Expand Down
2 changes: 1 addition & 1 deletion disnake/ext/commands/bot_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ class be provided, it must be similar enough to :class:`.Context`\'s

if prefix is None:
return ctx
elif isinstance(prefix, str):
if isinstance(prefix, str):
if not view.skip_string(prefix):
return ctx
else:
Expand Down
22 changes: 10 additions & 12 deletions disnake/ext/commands/common_bot_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,18 +154,16 @@ async def is_owner(self, user: Union[disnake.User, disnake.Member]) -> bool:
"""
if self.owner_id:
return user.id == self.owner_id
elif self.owner_ids:
if self.owner_ids:
return user.id in self.owner_ids
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
return user.id in self.owner_ids
return user.id in self.owner_ids

else:
app = await self.application_info() # type: ignore
if app.team:
self.owners = set(app.team.members)
self.owner_ids = ids = {m.id for m in app.team.members}
return user.id in ids
else:
self.owner = app.owner
self.owner_id = owner_id = app.owner.id
return user.id == owner_id
app = await self.application_info() # type: ignore
if app.team:
self.owners = set(app.team.members)
self.owner_ids = ids = {m.id for m in app.team.members}
return user.id in ids
self.owner = app.owner
self.owner_id = owner_id = app.owner.id
return user.id == owner_id

# listener registration

Expand Down Expand Up @@ -379,7 +377,7 @@ def remove_cog(self, name: str) -> Optional[Cog]:
"""
cog = self.__cogs.pop(name, None)
if cog is None:
return
return None

help_command: Optional[HelpCommand] = getattr(self, "_help_command", None)
if help_command and help_command.cog is cog:
Expand Down
Loading