Skip to content

Commit ed60240

Browse files
committed
Apply fixes for ruff linting
1 parent 2042485 commit ed60240

File tree

22 files changed

+75
-88
lines changed

22 files changed

+75
-88
lines changed

dev/bot/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,4 @@ class Bot(pydis_core.BotBase):
2121
async def setup_hook(self) -> None:
2222
"""Load extensions on startup."""
2323
await super().setup_hook()
24-
asyncio.create_task(self.load_extensions(sys.modules[__name__]))
24+
await self.load_extensions(sys.modules[__name__])

dev/bot/__main__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from discord.ext import commands
88

99
import pydis_core
10+
1011
from . import Bot
1112

1213
dotenv.load_dotenv()
@@ -17,7 +18,7 @@
1718

1819
bot = Bot(
1920
guild_id=int(os.getenv("GUILD_ID")),
20-
http_session=None, # type: ignore # We need to instantiate the session in an async context
21+
http_session=None, # type: ignore We need to instantiate the session in an async context
2122
allowed_roles=roles,
2223
command_prefix=commands.when_mentioned_or(os.getenv("PREFIX", "!")),
2324
intents=discord.Intents.all(),

dev/bot/cog.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def __init__(self, _bot: Bot):
1212
@commands.Cog.listener()
1313
async def on_ready(self) -> None:
1414
"""Print a message when the client (re)connects."""
15-
print("Client is ready.")
15+
print("Client is ready.") # noqa: T201
1616

1717
@commands.command()
1818
async def reload(self, ctx: commands.Context) -> None:

docs/conf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Configuration file for the Sphinx documentation builder.
22
# https://www.sphinx-doc.org/en/master/usage/configuration.html
33

4+
import contextlib
45
import functools
56
import os.path
67
import shutil
@@ -16,7 +17,7 @@
1617
logger = sphinx.util.logging.getLogger(__name__)
1718

1819
# Handle the path not being set correctly in actions.
19-
sys.path.insert(0, os.path.abspath('..'))
20+
sys.path.insert(0, os.path.abspath(".."))
2021

2122
from docs import utils # noqa: E402
2223

@@ -209,10 +210,9 @@ def _releases_setup(app: Sphinx) -> dict:
209210
smv_branch_whitelist = "main"
210211
if os.getenv("BUILD_DOCS_FOR_HEAD", "False").lower() == "true":
211212
if not (branch := os.getenv("BRANCH_NAME")):
212-
try:
213+
with contextlib.suppress(git.InvalidGitRepositoryError):
213214
branch = git.Repo(PROJECT_ROOT).active_branch.name
214-
except git.InvalidGitRepositoryError:
215-
pass
215+
216216

217217
if branch:
218218
logger.info(f"Adding branch {branch} to build whitelist.")

docs/netlify_build.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,5 @@
2222

2323
if __name__ == "__main__":
2424
# Run the build script
25-
print("Build started")
26-
subprocess.run([sys.executable, OUTPUT.absolute()])
25+
print("Build started") # noqa: T201
26+
subprocess.run([sys.executable, OUTPUT.absolute()]) # noqa: S603

docs/utils.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,15 @@ def get_build_root() -> Path:
3030
def is_attribute(module: types.ModuleType, parameter: str) -> bool:
3131
"""Returns true if `parameter` is an attribute of `module`."""
3232
docs = docstring_parser.parse(inspect.getdoc(module), docstring_parser.DocstringStyle.GOOGLE)
33-
for param in docs.params:
33+
for param in docs.params: # noqa: SIM110
3434
# The docstring_parser library can mis-parse arguments like `arg (:obj:`str`)` as `arg (`
3535
# which would create a false-negative below, so we just strip away the extra parenthesis.
3636
if param.args[0] == "attribute" and param.arg_name.rstrip(" (") == parameter:
3737
return True
38-
3938
return False
4039

4140

42-
def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typing.Optional[str]:
41+
def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> str | None:
4342
"""
4443
Function called by linkcode to get the URL for a given resource.
4544
@@ -79,8 +78,7 @@ def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typin
7978
# This could be caused by trying to link a class attribute
8079
if is_attribute(symbol[-1], name):
8180
break
82-
else:
83-
raise e
81+
raise e
8482

8583
symbol_name = name
8684

@@ -97,8 +95,8 @@ def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typin
9795
pos = _global_assign_pos(source, symbol_name)
9896
if pos is None:
9997
raise Exception(f"Could not find symbol `{symbol_name}` in {module.__name__}.")
100-
else:
101-
start, end = pos
98+
99+
start, end = pos
102100
_, offset = inspect.getsourcelines(symbol[-2])
103101
if offset != 0:
104102
offset -= 1
@@ -126,7 +124,7 @@ class NodeWithBody(typing.Protocol):
126124
body: list[ast.AST]
127125

128126

129-
def _global_assign_pos(ast_: NodeWithBody, name: str) -> typing.Union[tuple[int, int], None]:
127+
def _global_assign_pos(ast_: NodeWithBody, name: str) -> tuple[int, int] | None:
130128
"""
131129
Find the first instance where the `name` global is defined in `ast_`.
132130
@@ -149,6 +147,7 @@ def _global_assign_pos(ast_: NodeWithBody, name: str) -> typing.Union[tuple[int,
149147
pos_in_if = _global_assign_pos(ast_obj, name)
150148
if pos_in_if is not None:
151149
return pos_in_if
150+
return None
152151

153152

154153
def cleanup() -> None:
@@ -200,7 +199,7 @@ def build_api_doc() -> None:
200199
logger.info(f"Skipping api-doc for {output_folder.as_posix()} as it already exists.")
201200
return
202201

203-
result = subprocess.run(cmd, cwd=build_root, stdout=subprocess.PIPE, check=True, env=os.environ)
202+
result = subprocess.run(cmd, cwd=build_root, stdout=subprocess.PIPE, check=True, env=os.environ) # noqa: S603
204203
logger.debug("api-doc Output:\n" + result.stdout.decode(encoding="utf-8") + "\n")
205204

206205
cleanup()

pydis_core/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212
StartupError,
1313
]
1414

15-
__all__ = list(map(lambda module: module.__name__, __all__))
15+
__all__ = [module.__name__ for module in __all__]

pydis_core/_bot.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import types
44
import warnings
55
from contextlib import suppress
6-
from typing import Optional
76

87
import aiohttp
98
import discord
@@ -19,7 +18,7 @@
1918
from async_rediscache import RedisSession
2019
REDIS_AVAILABLE = True
2120
except ImportError:
22-
RedisSession = None
21+
RedisSession = object
2322
REDIS_AVAILABLE = False
2423

2524
log = get_logger()
@@ -42,9 +41,9 @@ def __init__(
4241
guild_id: int,
4342
allowed_roles: list,
4443
http_session: aiohttp.ClientSession,
45-
redis_session: Optional[RedisSession] = None,
46-
api_client: Optional[APIClient] = None,
47-
statsd_url: Optional[str] = None,
44+
redis_session: RedisSession | None = None,
45+
api_client: APIClient | None = None,
46+
statsd_url: str | None = None,
4847
**kwargs,
4948
):
5049
"""
@@ -77,16 +76,16 @@ def __init__(
7776
elif redis_session:
7877
self.redis_session = redis_session
7978

80-
self._resolver: Optional[aiohttp.AsyncResolver] = None
81-
self._connector: Optional[aiohttp.TCPConnector] = None
79+
self._resolver: aiohttp.AsyncResolver | None = None
80+
self._connector: aiohttp.TCPConnector | None = None
8281

83-
self._statsd_timerhandle: Optional[asyncio.TimerHandle] = None
84-
self._guild_available: Optional[asyncio.Event] = None
82+
self._statsd_timerhandle: asyncio.TimerHandle | None = None
83+
self._guild_available: asyncio.Event | None = None
8584
self._extension_loading_task: asyncio.Task | None = None
8685

87-
self.stats: Optional[AsyncStatsClient] = None
86+
self.stats: AsyncStatsClient | None = None
8887

89-
self.all_extensions: Optional[frozenset[str]] = None
88+
self.all_extensions: frozenset[str] | None = None
9089

9190
def _connect_statsd(
9291
self,
@@ -176,7 +175,7 @@ def add_command(self, command: commands.Command) -> None:
176175
super().add_command(command)
177176
self._add_root_aliases(command)
178177

179-
def remove_command(self, name: str) -> Optional[commands.Command]:
178+
def remove_command(self, name: str) -> commands.Command | None:
180179
"""
181180
Remove a command/alias as normal and then remove its root aliases from the bot.
182181

pydis_core/async_stats.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import asyncio
44
import socket
5-
from typing import Optional
65

76
from statsd.client.base import StatsClientBase
87

@@ -15,7 +14,7 @@ class AsyncStatsClient(StatsClientBase):
1514
def __init__(
1615
self,
1716
loop: asyncio.AbstractEventLoop,
18-
host: str = 'localhost',
17+
host: str = "localhost",
1918
port: int = 8125,
2019
prefix: str = None
2120
):
@@ -35,7 +34,7 @@ def __init__(
3534
self._addr = addr
3635
self._prefix = prefix
3736
self._loop = loop
38-
self._transport: Optional[asyncio.DatagramTransport] = None
37+
self._transport: asyncio.DatagramTransport | None = None
3938

4039
async def create_socket(self) -> None:
4140
"""Use :obj:`asyncio.loop.create_datagram_endpoint` from the loop given on init to create a socket."""
@@ -51,7 +50,7 @@ def _send(self, data: str) -> None:
5150

5251
async def _async_send(self, data: str) -> None:
5352
"""Send data to the statsd server using the async transport."""
54-
self._transport.sendto(data.encode('ascii'), self._addr)
53+
self._transport.sendto(data.encode("ascii"), self._addr)
5554

5655

57-
__all__ = ['AsyncStatsClient']
56+
__all__ = ["AsyncStatsClient"]

pydis_core/exts/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
"""Reusable Discord cogs."""
22
__all__ = []
33

4-
__all__ = list(map(lambda module: module.__name__, __all__))
4+
__all__ = [module.__name__ for module in __all__]

0 commit comments

Comments
 (0)