Skip to content

Commit

Permalink
Run black with experimental string processing (#1725)
Browse files Browse the repository at this point in the history
  • Loading branch information
BobDotCom authored Oct 24, 2022
1 parent 0de0652 commit 315082f
Show file tree
Hide file tree
Showing 53 changed files with 317 additions and 153 deletions.
9 changes: 5 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@ repos:
rev: 22.10.0
hooks:
- id: black
# See https://github.com/psf/black/issues/2188#issuecomment-1289317647 for why we can't use the --preview flag.
args: [--safe, --quiet]
# - repo: https://github.com/Pierre-Sassoulas/black-disable-checker
# rev: 1.0.1
# hooks:
# - id: black-disable-checker
- repo: https://github.com/Pierre-Sassoulas/black-disable-checker
rev: 1.0.1
hooks:
- id: black-disable-checker
# - repo: https://github.com/PyCQA/flake8
# rev: 4.0.1
# hooks:
Expand Down
6 changes: 4 additions & 2 deletions discord/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,8 @@ async def _edit(
for target, perm in overwrites.items():
if not isinstance(perm, PermissionOverwrite):
raise InvalidArgument(
f"Expected PermissionOverwrite received {perm.__class__.__name__}"
"Expected PermissionOverwrite received"
f" {perm.__class__.__name__}"
)

allow, deny = perm.pair()
Expand Down Expand Up @@ -1516,7 +1517,8 @@ async def send(
reference = reference.to_message_reference_dict()
except AttributeError:
raise InvalidArgument(
"reference parameter must be Message, MessageReference, or PartialMessage"
"reference parameter must be Message, MessageReference, or"
" PartialMessage"
) from None

if view:
Expand Down
8 changes: 6 additions & 2 deletions discord/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,10 @@ def __str__(self) -> str:
return "Spotify"

def __repr__(self) -> str:
return f"<Spotify title={self.title!r} artist={self.artist!r} track_id={self.track_id!r}>"
return (
"<Spotify"
f" title={self.title!r} artist={self.artist!r} track_id={self.track_id!r}>"
)

@property
def title(self) -> str:
Expand Down Expand Up @@ -790,7 +793,8 @@ def __init__(
self.emoji = emoji
else:
raise TypeError(
f"Expected str, PartialEmoji, or None, received {type(emoji)!r} instead."
"Expected str, PartialEmoji, or None, received"
f" {type(emoji)!r} instead."
)

@property
Expand Down
7 changes: 4 additions & 3 deletions discord/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,8 @@ def register(
if kwargs.pop("_log", True):
if method == "bulk":
_log.debug(
f"Bulk updating commands {[c['name'] for c in args[0]]} for guild {guild_id}"
f"Bulk updating commands {[c['name'] for c in args[0]]} for"
f" guild {guild_id}"
)
# TODO: Find where "cmd" is defined
elif method == "upsert":
Expand Down Expand Up @@ -636,7 +637,8 @@ def register(
)
if not cmd:
raise ValueError(
f"Registered command {i['name']}, type {i.get('type')} not found in pending commands"
f"Registered command {i['name']}, type {i.get('type')} not found in"
" pending commands"
)
cmd.id = i["id"]
self._application_commands[cmd.id] = cmd
Expand Down Expand Up @@ -831,7 +833,6 @@ async def process_application_commands(
if guild_id is None:
await self.sync_commands()
else:

await self.sync_commands(check_guilds=[guild_id])
return self._bot.dispatch("unknown_application_command", interaction)

Expand Down
5 changes: 4 additions & 1 deletion discord/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2061,7 +2061,10 @@ def __init__(
self._update(guild, data)

def __repr__(self) -> str:
return f"<CategoryChannel id={self.id} name={self.name!r} position={self.position} nsfw={self.nsfw}>"
return (
"<CategoryChannel"
f" id={self.id} name={self.name!r} position={self.position} nsfw={self.nsfw}>"
)

def _update(self, guild: Guild, data: CategoryChannelPayload) -> None:
# This data will always exist
Expand Down
4 changes: 2 additions & 2 deletions discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,6 @@ async def connect(self, *, reconnect: bool = True) -> None:
aiohttp.ClientError,
asyncio.TimeoutError,
) as exc:

self.dispatch("disconnect")
if not reconnect:
await self.close()
Expand Down Expand Up @@ -1768,7 +1767,8 @@ def add_view(self, view: View, *, message_id: int | None = None) -> None:

if not view.is_persistent():
raise ValueError(
"View is not persistent. Items need to have a custom_id set and View must have no timeout"
"View is not persistent. Items need to have a custom_id set and View"
" must have no timeout"
)

self._connection.store_view(view, message_id)
Expand Down
14 changes: 10 additions & 4 deletions discord/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,10 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:

commands = {}
listeners = {}
no_bot_cog = "Commands or listeners must not start with cog_ or bot_ (in method {0.__name__}.{1})"
no_bot_cog = (
"Commands or listeners must not start with cog_ or bot_ (in method"
" {0.__name__}.{1})"
)

new_cls = super().__new__(cls, name, bases, attrs, **kwargs)

Expand Down Expand Up @@ -177,7 +180,8 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
if isinstance(value, _filter):
if is_static_method:
raise TypeError(
f"Command in method {base}.{elem!r} must not be staticmethod."
f"Command in method {base}.{elem!r} must not be"
" staticmethod."
)
if elem.startswith(("cog_", "bot_")):
raise TypeError(no_bot_cog.format(base, elem))
Expand All @@ -187,7 +191,8 @@ def __new__(cls: type[CogMeta], *args: Any, **kwargs: Any) -> CogMeta:
if hasattr(value, "add_to") and not getattr(value, "parent", None):
if is_static_method:
raise TypeError(
f"Command in method {base}.{elem!r} must not be staticmethod."
f"Command in method {base}.{elem!r} must not be"
" staticmethod."
)
if elem.startswith(("cog_", "bot_")):
raise TypeError(no_bot_cog.format(base, elem))
Expand Down Expand Up @@ -386,7 +391,8 @@ def listener(cls, name: str = MISSING) -> Callable[[FuncT], FuncT]:

if name is not MISSING and not isinstance(name, str):
raise TypeError(
f"Cog.listener expected str but received {name.__class__.__name__!r} instead."
"Cog.listener expected str but received"
f" {name.__class__.__name__!r} instead."
)

def decorator(func: FuncT) -> FuncT:
Expand Down
6 changes: 4 additions & 2 deletions discord/commands/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,8 @@ def send_response(self) -> Callable[..., Awaitable[Interaction]]:
return self.interaction.response.send_message
else:
raise RuntimeError(
f"Interaction was already issued a response. Try using {type(self).__name__}.send_followup() instead."
"Interaction was already issued a response. Try using"
f" {type(self).__name__}.send_followup() instead."
)

@property
Expand All @@ -304,7 +305,8 @@ def send_followup(self) -> Callable[..., Awaitable[WebhookMessage]]:
return self.followup.send
else:
raise RuntimeError(
f"Interaction was not yet issued a response. Try using {type(self).__name__}.respond() first."
"Interaction was not yet issued a response. Try using"
f" {type(self).__name__}.respond() first."
)

@property
Expand Down
19 changes: 12 additions & 7 deletions discord/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,6 @@ async def invoke(self, ctx: ApplicationContext) -> None:
await injected(ctx)

async def can_run(self, ctx: ApplicationContext) -> bool:

if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.name} failed."
Expand Down Expand Up @@ -1822,7 +1821,8 @@ def validate_chat_input_name(name: Any, locale: str | None = None):
# Must meet the regex ^[-_\w\d\u0901-\u097D\u0E00-\u0E7F]{1,32}$
if locale is not None and locale not in valid_locales:
raise ValidationError(
f"Locale '{locale}' is not a valid locale, see {docs}/reference#locales for list of supported locales."
f"Locale '{locale}' is not a valid locale, see {docs}/reference#locales for"
" list of supported locales."
)
error = None
if not isinstance(name, str):
Expand All @@ -1831,8 +1831,10 @@ def validate_chat_input_name(name: Any, locale: str | None = None):
)
elif not re.match(r"^[-_\w\d\u0901-\u097D\u0E00-\u0E7F]{1,32}$", name):
error = ValidationError(
r"Command names and options must follow the regex \"^[-_\w\d\u0901-\u097D\u0E00-\u0E7F]{1,32}$\". "
f"For more information, see {docs}/interactions/application-commands#application-command-object-"
r"Command names and options must follow the regex"
r" \"^[-_\w\d\u0901-\u097D\u0E00-\u0E7F]{1,32}$\". "
"For more information, see"
f" {docs}/interactions/application-commands#application-command-object-"
f'application-command-naming. Received "{name}"'
)
elif (
Expand All @@ -1851,16 +1853,19 @@ def validate_chat_input_name(name: Any, locale: str | None = None):
def validate_chat_input_description(description: Any, locale: str | None = None):
if locale is not None and locale not in valid_locales:
raise ValidationError(
f"Locale '{locale}' is not a valid locale, see {docs}/reference#locales for list of supported locales."
f"Locale '{locale}' is not a valid locale, see {docs}/reference#locales for"
" list of supported locales."
)
error = None
if not isinstance(description, str):
error = TypeError(
f'Command and option description must be of type str. Received "{description}"'
"Command and option description must be of type str. Received"
f' "{description}"'
)
elif not 1 <= len(description) <= 100:
error = ValidationError(
f'Command and option description must be 1-100 characters long. Received "{description}"'
"Command and option description must be 1-100 characters long. Received"
f' "{description}"'
)

if error:
Expand Down
6 changes: 4 additions & 2 deletions discord/commands/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,11 +278,13 @@ def __init__(

if self.min_value is not None and not isinstance(self.min_value, minmax_types):
raise TypeError(
f'Expected {minmax_typehint} for min_value, got "{type(self.min_value).__name__}"'
f"Expected {minmax_typehint} for min_value, got"
f' "{type(self.min_value).__name__}"'
)
if self.max_value is not None and not isinstance(self.max_value, minmax_types):
raise TypeError(
f'Expected {minmax_typehint} for max_value, got "{type(self.max_value).__name__}"'
f"Expected {minmax_typehint} for max_value, got"
f' "{type(self.max_value).__name__}"'
)

if self.min_length is not None:
Expand Down
6 changes: 4 additions & 2 deletions discord/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,8 @@ def __init__(

def __repr__(self) -> str:
return (
f"<SelectOption label={self.label!r} value={self.value!r} description={self.description!r} "
"<SelectOption"
f" label={self.label!r} value={self.value!r} description={self.description!r} "
f"emoji={self.emoji!r} default={self.default!r}>"
)

Expand All @@ -430,7 +431,8 @@ def emoji(self, value) -> None:
value = value._to_partial()
else:
raise TypeError(
f"expected emoji to be str, Emoji, or PartialEmoji not {value.__class__}"
"expected emoji to be str, Emoji, or PartialEmoji not"
f" {value.__class__}"
)

self._emoji = value
Expand Down
7 changes: 4 additions & 3 deletions discord/embeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,6 @@ def __init__(
timestamp: datetime.datetime = None,
fields: list[EmbedField] | None = None,
):

self.colour = colour if colour is not EmptyEmbed else color
self.title = title
self.type = type
Expand Down Expand Up @@ -402,7 +401,8 @@ def colour(self, value: int | Colour | _EmptyEmbed): # type: ignore
self._colour = Colour(value=value)
else:
raise TypeError(
f"Expected discord.Colour, int, or Embed.Empty but received {value.__class__.__name__} instead."
"Expected discord.Colour, int, or Embed.Empty but received"
f" {value.__class__.__name__} instead."
)

color = colour
Expand All @@ -421,7 +421,8 @@ def timestamp(self, value: MaybeEmpty[datetime.datetime]):
self._timestamp = value
else:
raise TypeError(
f"Expected datetime.datetime or Embed.Empty received {value.__class__.__name__} instead"
"Expected datetime.datetime or Embed.Empty received"
f" {value.__class__.__name__} instead"
)

@property
Expand Down
5 changes: 4 additions & 1 deletion discord/emoji.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,10 @@ def __str__(self) -> str:
return f"<:{self.name}:{self.id}>"

def __repr__(self) -> str:
return f"<Emoji id={self.id} name={self.name!r} animated={self.animated} managed={self.managed}>"
return (
"<Emoji"
f" id={self.id} name={self.name!r} animated={self.animated} managed={self.managed}>"
)

def __eq__(self, other: Any) -> bool:
return isinstance(other, _EmojiTag) and self.id == other.id
Expand Down
14 changes: 9 additions & 5 deletions discord/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,11 @@ class PrivilegedIntentsRequired(ClientException):
def __init__(self, shard_id: int | None):
self.shard_id: int | None = shard_id
msg = (
"Shard ID %s is requesting privileged intents that have not been explicitly enabled in the "
"developer portal. It is recommended to go to https://discord.com/developers/applications/ "
"and explicitly enable the privileged intents within your application's page. If this is not "
"possible, then consider disabling the privileged intents instead."
"Shard ID %s is requesting privileged intents that have not been explicitly"
" enabled in the developer portal. It is recommended to go to"
" https://discord.com/developers/applications/ and explicitly enable the"
" privileged intents within your application's page. If this is not"
" possible, then consider disabling the privileged intents instead."
)
super().__init__(msg % shard_id)

Expand Down Expand Up @@ -349,7 +350,10 @@ class ExtensionFailed(ExtensionError):

def __init__(self, name: str, original: Exception) -> None:
self.original: Exception = original
msg = f"Extension {name!r} raised an error: {original.__class__.__name__}: {original}"
msg = (
f"Extension {name!r} raised an error: {original.__class__.__name__}:"
f" {original}"
)
super().__init__(msg, name=name)


Expand Down
3 changes: 2 additions & 1 deletion discord/ext/bridge/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,8 @@ async def convert(self, ctx, argument: str) -> Any:
choices = [choice.value for choice in self.choices]
if converted not in choices:
raise ValueError(
f"{argument} is not a valid choice. Valid choices: {list(set(choices_names + choices))}"
f"{argument} is not a valid choice. Valid choices:"
f" {list(set(choices_names + choices))}"
)

return converted
Expand Down
9 changes: 5 additions & 4 deletions discord/ext/commands/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ async def get_prefix(self, message: Message) -> list[str] | str:
raise

raise TypeError(
"command_prefix must be plain string, iterable of strings, or callable "
f"returning either of these, not {ret.__class__.__name__}"
"command_prefix must be plain string, iterable of strings, or"
f" callable returning either of these, not {ret.__class__.__name__}"
)

if not ret:
Expand Down Expand Up @@ -311,8 +311,9 @@ class be provided, it must be similar enough to :class:`.Context`\'s
for value in prefix:
if not isinstance(value, str):
raise TypeError(
"Iterable command_prefix or list returned from get_prefix must "
f"contain only strings, not {value.__class__.__name__}"
"Iterable command_prefix or list returned from get_prefix"
" must contain only strings, not"
f" {value.__class__.__name__}"
)

# Getting here shouldn't happen
Expand Down
5 changes: 4 additions & 1 deletion discord/ext/commands/cooldowns.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,10 @@ def copy(self) -> Cooldown:
return Cooldown(self.rate, self.per)

def __repr__(self) -> str:
return f"<Cooldown rate: {self.rate} per: {self.per} window: {self._window} tokens: {self._tokens}>"
return (
f"<Cooldown rate: {self.rate} per: {self.per} window:"
f" {self._window} tokens: {self._tokens}>"
)


class CooldownMapping:
Expand Down
3 changes: 2 additions & 1 deletion discord/ext/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1178,7 +1178,8 @@ async def can_run(self, ctx: Context) -> bool:
try:
if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.qualified_name} failed."
"The global check functions for command"
f" {self.qualified_name} failed."
)

cog = self.cog
Expand Down
Loading

0 comments on commit 315082f

Please sign in to comment.