Add More ruff Rules (#3763)

This commit is contained in:
Harshil 2023-06-29 15:08:09 +05:30 committed by GitHub
parent 4a6e0fd7a6
commit 58b89cf0e9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 30 additions and 21 deletions

View file

@ -77,7 +77,7 @@ repos:
- --diff - --diff
- --check - --check
- repo: https://github.com/charliermarsh/ruff-pre-commit - repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.270' rev: 'v0.0.275'
hooks: hooks:
- id: ruff - id: ruff
name: ruff name: ruff

View file

@ -12,7 +12,10 @@ target-version = "py37"
show-fixes = true show-fixes = true
ignore = ["PLR2004", "PLR0911", "PLR0912", "PLR0913", "PLR0915"] ignore = ["PLR2004", "PLR0911", "PLR0912", "PLR0913", "PLR0915"]
select = ["E", "F", "I", "PL", "UP", "RUF", "PTH", "C4", "B", "PIE", "SIM", "RET", "RSE", select = ["E", "F", "I", "PL", "UP", "RUF", "PTH", "C4", "B", "PIE", "SIM", "RET", "RSE",
"G", "ISC", "PT"] "G", "ISC", "PT", "ASYNC", "TCH", "CPY", "SLOT", "PERF",]
[tool.ruff.per-file-ignores] [tool.ruff.per-file-ignores]
"tests/*.py" = ["B018"] "tests/*.py" = ["B018"]
"**/__init__.py" = ["CPY001"]
"examples/**.py" = ["CPY001"]
"tests/**.py" = ["RUF012"]

View file

@ -18,15 +18,17 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InputSticker.""" """This module contains an object that represents a Telegram InputSticker."""
from typing import Optional, Sequence, Tuple, Union from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union
from telegram._files.inputfile import InputFile
from telegram._files.sticker import MaskPosition from telegram._files.sticker import MaskPosition
from telegram._telegramobject import TelegramObject from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import parse_sequence_arg from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.files import parse_file_input from telegram._utils.files import parse_file_input
from telegram._utils.types import FileInput, JSONDict from telegram._utils.types import FileInput, JSONDict
if TYPE_CHECKING:
from telegram._files.inputfile import InputFile
class InputSticker(TelegramObject): class InputSticker(TelegramObject):
""" """

View file

@ -28,6 +28,7 @@ from types import MappingProxyType
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
ClassVar,
Dict, Dict,
Iterator, Iterator,
List, List,
@ -92,7 +93,7 @@ class TelegramObject:
# Used to cache the names of the parameters of the __init__ method of the class # Used to cache the names of the parameters of the __init__ method of the class
# Must be a private attribute to avoid name clashes between subclasses # Must be a private attribute to avoid name clashes between subclasses
__INIT_PARAMS: Set[str] = set() __INIT_PARAMS: ClassVar[Set[str]] = set()
# Used to check if __INIT_PARAMS has been set for the current class. Unfortunately, we can't # Used to check if __INIT_PARAMS has been set for the current class. Unfortunately, we can't
# just check if `__INIT_PARAMS is None`, since subclasses use the parent class' __INIT_PARAMS # just check if `__INIT_PARAMS is None`, since subclasses use the parent class' __INIT_PARAMS
# unless it's overridden # unless it's overridden

View file

@ -196,12 +196,11 @@ class AIORateLimiter(BaseRateLimiter[int]):
self._get_group_limiter(group) if group and self._group_max_rate else null_context() self._get_group_limiter(group) if group and self._group_max_rate else null_context()
) )
async with group_context: # skipcq: PTC-W0062 async with group_context, base_context:
async with base_context: # In case a retry_after was hit, we wait with processing the request
# In case a retry_after was hit, we wait with processing the request await self._retry_after_event.wait()
await self._retry_after_event.wait()
return await callback(*args, **kwargs) return await callback(*args, **kwargs)
# mypy doesn't understand that the last run of the for loop raises an exception # mypy doesn't understand that the last run of the for loop raises an exception
async def process_request( async def process_request(

View file

@ -58,7 +58,6 @@ from telegram._utils.warnings import warn
from telegram.error import TelegramError from telegram.error import TelegramError
from telegram.ext._basehandler import BaseHandler from telegram.ext._basehandler import BaseHandler
from telegram.ext._basepersistence import BasePersistence from telegram.ext._basepersistence import BasePersistence
from telegram.ext._baseupdateprocessor import BaseUpdateProcessor
from telegram.ext._contexttypes import ContextTypes from telegram.ext._contexttypes import ContextTypes
from telegram.ext._extbot import ExtBot from telegram.ext._extbot import ExtBot
from telegram.ext._updater import Updater from telegram.ext._updater import Updater
@ -70,6 +69,7 @@ if TYPE_CHECKING:
from telegram import Message from telegram import Message
from telegram.ext import ConversationHandler, JobQueue from telegram.ext import ConversationHandler, JobQueue
from telegram.ext._applicationbuilder import InitApplicationBuilder from telegram.ext._applicationbuilder import InitApplicationBuilder
from telegram.ext._baseupdateprocessor import BaseUpdateProcessor
from telegram.ext._jobqueue import Job from telegram.ext._jobqueue import Job
DEFAULT_GROUP: int = 0 DEFAULT_GROUP: int = 0

View file

@ -19,12 +19,14 @@
"""This module contains the DictPersistence class.""" """This module contains the DictPersistence class."""
import json import json
from copy import deepcopy from copy import deepcopy
from typing import Any, Dict, Optional, cast from typing import TYPE_CHECKING, Any, Dict, Optional, cast
from telegram._utils.types import JSONDict
from telegram.ext import BasePersistence, PersistenceInput from telegram.ext import BasePersistence, PersistenceInput
from telegram.ext._utils.types import CDCData, ConversationDict, ConversationKey from telegram.ext._utils.types import CDCData, ConversationDict, ConversationKey
if TYPE_CHECKING:
from telegram._utils.types import JSONDict
class DictPersistence(BasePersistence[Dict[Any, Any], Dict[Any, Any], Dict[Any, Any]]): class DictPersistence(BasePersistence[Dict[Any, Any], Dict[Any, Any], Dict[Any, Any]]):
"""Using Python's :obj:`dict` and :mod:`json` for making your bot persistent. """Using Python's :obj:`dict` and :mod:`json` for making your bot persistent.

View file

@ -25,7 +25,6 @@ from typing import TYPE_CHECKING, Any, Generic, Optional, Tuple, Union, cast, ov
try: try:
import pytz import pytz
from apscheduler.executors.asyncio import AsyncIOExecutor from apscheduler.executors.asyncio import AsyncIOExecutor
from apscheduler.job import Job as APSJob
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.asyncio import AsyncIOScheduler
APS_AVAILABLE = True APS_AVAILABLE = True
@ -38,6 +37,9 @@ from telegram.ext._extbot import ExtBot
from telegram.ext._utils.types import CCT, JobCallback from telegram.ext._utils.types import CCT, JobCallback
if TYPE_CHECKING: if TYPE_CHECKING:
if APS_AVAILABLE:
from apscheduler.job import Job as APSJob
from telegram.ext import Application from telegram.ext import Application

View file

@ -60,13 +60,13 @@ def check_thumb_deprecation_warnings_for_args_and_attrs(
for i in range(expected_recwarn_length): for i in range(expected_recwarn_length):
assert issubclass(recwarn[i].category, PTBDeprecationWarning) assert issubclass(recwarn[i].category, PTBDeprecationWarning)
assert f"{names[i]} '{deprecated_name}' to '{new_name}'" in str(recwarn[i].message), ( assert f"{names[i]} '{deprecated_name}' to '{new_name}'" in str(recwarn[i].message), (
f'Warning issued by file {recwarn[i].filename} ("{str(recwarn[i].message)}") ' f'Warning issued by file {recwarn[i].filename} ("{recwarn[i].message}") '
"does not contain expected phrase: " "does not contain expected phrase: "
f"\"{names[i]} '{deprecated_name}' to '{new_name}'\"" f"\"{names[i]} '{deprecated_name}' to '{new_name}'\""
) )
assert recwarn[i].filename == calling_file, ( assert recwarn[i].filename == calling_file, (
f'Warning for {names[i]} ("{str(recwarn[i].message)}") was issued by file ' f'Warning for {names[i]} ("{recwarn[i].message}") was issued by file '
f"{recwarn[i].filename}, expected {calling_file}" f"{recwarn[i].filename}, expected {calling_file}"
) )

View file

@ -492,7 +492,7 @@ class TestJobQueue:
job_2 = job_queue.run_repeating(self.job_run_once, 0.2) job_2 = job_queue.run_repeating(self.job_run_once, 0.2)
job_3 = Job(self.job_run_once, 0.2) job_3 = Job(self.job_run_once, 0.2)
job_3._job = job.job job_3._job = job.job
assert job == job assert job == job # noqa: PLR0124
assert job != job_queue assert job != job_queue
assert job != job_2 assert job != job_2
assert job == job_3 assert job == job_3

View file

@ -206,7 +206,7 @@ class TestChatPermissionsWithoutRequest(TestChatPermissionsBase):
def test_equality_warning(self, recwarn, chat_permissions): def test_equality_warning(self, recwarn, chat_permissions):
recwarn.clear() recwarn.clear()
assert chat_permissions == chat_permissions assert chat_permissions == ChatPermissions.all_permissions()
assert str(recwarn[0].message) == ( assert str(recwarn[0].message) == (
"In v21, granular media settings will be considered as well when comparing" "In v21, granular media settings will be considered as well when comparing"

View file

@ -136,7 +136,7 @@ class TestKeyboardButtonWithoutRequest(TestKeyboardButtonBase):
def test_equality_warning(self, recwarn, keyboard_button): def test_equality_warning(self, recwarn, keyboard_button):
recwarn.clear() recwarn.clear()
assert keyboard_button == keyboard_button assert keyboard_button == keyboard_button # noqa: PLR0124
assert str(recwarn[0].message) == ( assert str(recwarn[0].message) == (
"In v21, `request_user` and `request_chat` will be considered as well when comparing" "In v21, `request_user` and `request_chat` will be considered as well when comparing"

View file

@ -37,7 +37,7 @@ def test_class_has_slots_and_no_dict():
for name, cls in inspect.getmembers(module, inspect.isclass): for name, cls in inspect.getmembers(module, inspect.isclass):
if cls.__module__ != module.__name__ or any( # exclude 'imported' modules if cls.__module__ != module.__name__ or any( # exclude 'imported' modules
x in name for x in {"__class__", "__init__", "Queue", "Webhook"} x in name for x in ("__class__", "__init__", "Queue", "Webhook")
): ):
continue continue
@ -46,7 +46,7 @@ def test_class_has_slots_and_no_dict():
assert not isinstance(cls.__slots__, str), f"{name!r}s slots shouldn't be strings" assert not isinstance(cls.__slots__, str), f"{name!r}s slots shouldn't be strings"
# specify if a certain module/class/base class should have dict- # specify if a certain module/class/base class should have dict-
if any(i in included for i in {cls.__module__, name, cls.__base__.__name__}): if any(i in included for i in (cls.__module__, name, cls.__base__.__name__)):
assert "__dict__" in get_slots(cls), f"class {name!r} ({path}) has no __dict__" assert "__dict__" in get_slots(cls), f"class {name!r} ({path}) has no __dict__"
continue continue