Skip to content

Bump ruff and add new rules #4416

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

Merged
merged 4 commits into from
Aug 7, 2024
Merged
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ ci:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 'v0.5.0'
rev: 'v0.5.6'
hooks:
- id: ruff
name: ruff
Expand Down
5 changes: 2 additions & 3 deletions docs/auxil/sphinx_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import collections.abc
import contextlib
import inspect
import re
import typing
Expand Down Expand Up @@ -153,13 +154,11 @@ def autodoc_process_docstring(
if isinstance(obj, telegram.ext.filters.BaseFilter):
obj = obj.__class__

try:
with contextlib.suppress(Exception):
source_lines, start_line = inspect.getsourcelines(obj)
end_line = start_line + len(source_lines)
file = Path(inspect.getsourcefile(obj)).relative_to(FILE_ROOT)
LINE_NUMBERS[name] = (file, start_line, end_line)
except Exception:
pass

# Since we don't document the `__init__`, we call this manually to have it available for
# attributes -- see the note above
Expand Down
3 changes: 2 additions & 1 deletion docs/auxil/tg_const_role.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ def process_link(
refnode.rawsource,
CONSTANTS_ROLE,
)
return title, target
except Exception as exc:
sphinx_logger.exception(
"%s:%d: WARNING: Did not convert reference %s due to an exception.",
Expand All @@ -98,3 +97,5 @@ def process_link(
exc_info=exc,
)
return title, target
else:
return title, target
15 changes: 11 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,21 @@ explicit-preview-rules = true # TODO: Drop this when RUF022 and RUF023 are out
ignore = ["PLR2004", "PLR0911", "PLR0912", "PLR0913", "PLR0915", "PERF203"]
select = ["E", "F", "I", "PL", "UP", "RUF", "PTH", "C4", "B", "PIE", "SIM", "RET", "RSE",
"G", "ISC", "PT", "ASYNC", "TCH", "SLOT", "PERF", "PYI", "FLY", "AIR", "RUF022",
"RUF023", "Q", "INP", "W", "YTT", "DTZ", "ARG", "T20", "FURB"]
"RUF023", "Q", "INP", "W", "YTT", "DTZ", "ARG", "T20", "FURB", "DOC", "TRY",
"D100", "D101", "D102", "D103", "D300", "D418", "D419", "S"]
# Add "A (flake8-builtins)" after we drop pylint

[tool.ruff.lint.per-file-ignores]
"tests/*.py" = ["B018"]
"tests/**.py" = ["RUF012", "ASYNC230", "DTZ", "ARG", "T201"]
"docs/**.py" = ["INP001", "ARG"]
"examples/**.py" = ["ARG"]
"tests/**.py" = ["RUF012", "ASYNC230", "DTZ", "ARG", "T201", "ASYNC109", "D", "S", "TRY"]
"telegram/**.py" = ["TRY003"]
"telegram/ext/_applicationbuilder.py" = ["TRY004"]
"telegram/ext/filters.py" = ["D102"]
"docs/**.py" = ["INP001", "ARG", "D", "TRY003", "S"]
"examples/**.py" = ["ARG", "D", "S105", "TRY003"]

[tool.ruff.lint.pydocstyle]
convention = "google"

# PYLINT:
[tool.pylint."messages control"]
Expand Down
2 changes: 1 addition & 1 deletion telegram/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=missing-module-docstring
# ruff: noqa: T201
# ruff: noqa: T201, D100, S603, S607
import subprocess
import sys
from typing import Optional
Expand Down
10 changes: 5 additions & 5 deletions telegram/_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,10 +324,10 @@ async def __aenter__(self: BT) -> BT:
"""
try:
await self.initialize()
return self
except Exception as exc:
except Exception:
await self.shutdown()
raise exc
raise
return self

async def __aexit__(
self,
Expand Down Expand Up @@ -4271,7 +4271,7 @@ async def get_updates(
self,
offset: Optional[int] = None,
limit: Optional[int] = None,
timeout: Optional[int] = None,
timeout: Optional[int] = None, # noqa: ASYNC109
allowed_updates: Optional[Sequence[str]] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
Expand Down Expand Up @@ -4387,7 +4387,7 @@ async def get_updates(
self._LOGGER.critical(
"Error while parsing updates! Received data was %r", result, exc_info=exc
)
raise exc
raise

async def set_webhook(
self,
Expand Down
2 changes: 1 addition & 1 deletion telegram/_telegramobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ def _de_json(
obj = cls(**data, api_kwargs=api_kwargs)
except TypeError as exc:
if "__init__() got an unexpected keyword argument" not in str(exc):
raise exc
raise

if cls.__INIT_PARAMS_CHECK is not cls:
signature = inspect.signature(cls)
Expand Down
2 changes: 1 addition & 1 deletion telegram/ext/_aioratelimiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ async def process_request(
_LOGGER.exception(
"Rate limit hit after maximum of %d retries", max_retries, exc_info=exc
)
raise exc
raise

sleep = exc.retry_after + 0.1
_LOGGER.info("Rate limit hit. Retrying after %f seconds", sleep)
Expand Down
23 changes: 13 additions & 10 deletions telegram/ext/_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,10 +384,10 @@ async def __aenter__(self: _AppType) -> _AppType: # noqa: PYI019
"""
try:
await self.initialize()
return self
except Exception as exc:
except Exception:
await self.shutdown()
raise exc
raise
return self

async def __aexit__(
self,
Expand Down Expand Up @@ -646,9 +646,9 @@ async def start(self) -> None:
)
_LOGGER.info("Application started")

except Exception as exc:
except Exception:
self._running = False
raise exc
raise

async def stop(self) -> None:
"""Stops the process after processing any pending updates or tasks created by
Expand Down Expand Up @@ -1227,7 +1227,7 @@ async def __create_task_callback(
await self.process_error(update=update, error=exception, coroutine=coroutine)

# Raise exception so that it can be set on the task and retrieved by task.exception()
raise exception
raise
finally:
self._mark_for_persistence_update(update=update)

Expand Down Expand Up @@ -1445,14 +1445,16 @@ def add_handlers(
1: [CallbackQueryHandler(...), CommandHandler(...)]
}

Raises:
:exc:`TypeError`: If the combination of arguments is invalid.
"""
if isinstance(handlers, dict) and not isinstance(group, DefaultValue):
raise ValueError("The `group` argument can only be used with a sequence of handlers.")
raise TypeError("The `group` argument can only be used with a sequence of handlers.")

if isinstance(handlers, dict):
for handler_group, grp_handlers in handlers.items():
if not isinstance(grp_handlers, (list, tuple)):
raise ValueError(f"Handlers for group {handler_group} must be a list or tuple")
raise TypeError(f"Handlers for group {handler_group} must be a list or tuple")

for handler in grp_handlers:
self.add_handler(handler, handler_group)
Expand All @@ -1462,7 +1464,7 @@ def add_handlers(
self.add_handler(handler, DefaultValue.get_value(group))

else:
raise ValueError(
raise TypeError(
"The `handlers` argument must be a sequence of handlers or a "
"dictionary where the keys are groups and values are sequences of handlers."
)
Expand Down Expand Up @@ -1644,9 +1646,10 @@ async def _persistence_updater(self) -> None:
self.__update_persistence_event.wait(),
timeout=self.persistence.update_interval,
)
return
except asyncio.TimeoutError:
pass
else:
return

# putting this *after* the wait_for so we don't immediately update on startup as
# that would make little sense
Expand Down
2 changes: 1 addition & 1 deletion telegram/ext/_applicationbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def __init__(self: "InitApplicationBuilder"):
self._job_queue: ODVInput[JobQueue] = DefaultValue(JobQueue())
except RuntimeError as exc:
if "PTB must be installed via" not in str(exc):
raise exc
raise
self._job_queue = DEFAULT_NONE

self._persistence: ODVInput[BasePersistence] = DEFAULT_NONE
Expand Down
6 changes: 3 additions & 3 deletions telegram/ext/_baseupdateprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@ async def __aenter__(self: _BUPT) -> _BUPT: # noqa: PYI019
"""
try:
await self.initialize()
return self
except Exception as exc:
except Exception:
await self.shutdown()
raise exc
raise
return self

async def __aexit__(
self,
Expand Down
4 changes: 3 additions & 1 deletion telegram/ext/_callbackcontext.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,9 @@ def drop_callback_data(self, callback_query: CallbackQuery) -> None:
)
self.bot.callback_data_cache.drop_data(callback_query)
else:
raise RuntimeError("telegram.Bot does not allow for arbitrary callback data.")
raise RuntimeError( # noqa: TRY004
"telegram.Bot does not allow for arbitrary callback data."
)

@classmethod
def from_error(
Expand Down
2 changes: 1 addition & 1 deletion telegram/ext/_callbackdatacache.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,9 @@ def __get_keyboard_uuid_and_button_data(
button_data = keyboard_data.button_data[button]
# Update the timestamp for the LRU
keyboard_data.update_access_time()
return keyboard, button_data
except KeyError:
return None, InvalidCallbackData(callback_data)
return keyboard, button_data

@staticmethod
def extract_uuids(callback_data: str) -> Tuple[str, str]:
Expand Down
2 changes: 1 addition & 1 deletion telegram/ext/_contexttypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def __init__( # type: ignore[misc]
user_data: Type[ADict] = dict,
):
if not issubclass(context, CallbackContext):
raise ValueError("context must be a subclass of CallbackContext.")
raise TypeError("context must be a subclass of CallbackContext.")

# We make all those only accessible via properties because we don't currently support
# changing this at runtime, so overriding the attributes doesn't make sense
Expand Down
2 changes: 1 addition & 1 deletion telegram/ext/_extbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ async def get_updates(
self,
offset: Optional[int] = None,
limit: Optional[int] = None,
timeout: Optional[int] = None,
timeout: Optional[int] = None, # noqa: ASYNC109
allowed_updates: Optional[Sequence[str]] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
Expand Down
38 changes: 18 additions & 20 deletions telegram/ext/_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,10 @@ async def __aenter__(self: _UpdaterType) -> _UpdaterType: # noqa: PYI019
"""
try:
await self.initialize()
return self
except Exception as exc:
except Exception:
await self.shutdown()
raise exc
raise
return self

async def __aexit__(
self,
Expand Down Expand Up @@ -214,7 +214,7 @@ async def shutdown(self) -> None:
async def start_polling(
self,
poll_interval: float = 0.0,
timeout: int = 10,
timeout: int = 10, # noqa: ASYNC109
bootstrap_retries: int = -1,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
Expand Down Expand Up @@ -339,16 +339,15 @@ def callback(error: telegram.error.TelegramError)
_LOGGER.debug("Waiting for polling to start")
await polling_ready.wait()
_LOGGER.debug("Polling updates from Telegram started")

return self.update_queue
except Exception as exc:
except Exception:
self._running = False
raise exc
raise
return self.update_queue

async def _start_polling(
self,
poll_interval: float,
timeout: int,
timeout: int, # noqa: ASYNC109
read_timeout: ODVInput[float],
write_timeout: ODVInput[float],
connect_timeout: ODVInput[float],
Expand Down Expand Up @@ -384,9 +383,9 @@ async def polling_action_cb() -> bool:
pool_timeout=pool_timeout,
allowed_updates=allowed_updates,
)
except TelegramError as exc:
except TelegramError:
# TelegramErrors should be processed by the network retry loop
raise exc
raise
except Exception as exc:
# Other exceptions should not. Let's log them for now.
_LOGGER.critical(
Expand Down Expand Up @@ -446,13 +445,12 @@ async def _get_updates_cleanup() -> None:
pool_timeout=pool_timeout,
allowed_updates=allowed_updates,
)
except TelegramError as exc:
_LOGGER.error(
except TelegramError:
_LOGGER.exception(
"Error while calling `get_updates` one more time to mark all fetched updates "
"as read: %s. Suppressing error to ensure graceful shutdown. When polling for "
"updates is restarted, updates may be fetched again. Please adjust timeouts "
"via `ApplicationBuilder` or the parameter `get_updates_request` of `Bot`.",
exc_info=exc,
)

self.__polling_cleanup_cb = _get_updates_cleanup
Expand Down Expand Up @@ -623,9 +621,9 @@ async def start_webhook(
_LOGGER.debug("Waiting for webhook server to start")
await webhook_ready.wait()
_LOGGER.debug("Webhook server started")
except Exception as exc:
except Exception:
self._running = False
raise exc
raise

# Return the update queue so the main thread can insert updates
return self.update_queue
Expand Down Expand Up @@ -761,11 +759,11 @@ async def do_action() -> bool:
_LOGGER.debug("Timed out %s: %s", description, toe)
# If failure is due to timeout, we should retry asap.
cur_interval = 0
except InvalidToken as pex:
_LOGGER.error("Invalid token; aborting")
raise pex
except InvalidToken:
_LOGGER.exception("Invalid token; aborting")
raise
except TelegramError as telegram_exc:
_LOGGER.error("Error while %s: %s", description, telegram_exc)
_LOGGER.exception("Error while %s:", description)
on_err_cb(telegram_exc)

# increase waiting times on subsequent errors up to 30secs
Expand Down
Loading
Loading