Skip to content

Commit

Permalink
General cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
LilSpazJoekp committed Oct 22, 2023
1 parent 2f84d28 commit cd63b50
Show file tree
Hide file tree
Showing 35 changed files with 156 additions and 138 deletions.
5 changes: 2 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ repos:
types: [ python ]

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: check-executables-have-shebangs
Expand All @@ -33,7 +33,6 @@ repos:
- id: name-tests-test
args: [ --pytest-test-first ]
files: ^tests/integration/.*\.py|tests/unit/.*\.py$
- id: no-commit-to-branch
- id: sort-simple-yaml
files: ^(\.github/workflows/.*\.ya?ml|\.readthedocs.ya?ml)$
- id: trailing-whitespace
Expand All @@ -45,7 +44,7 @@ repos:
files: ^(.*\.toml)$

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.286
rev: v0.0.292
hooks:
- id: ruff
args: [ --exit-non-zero-on-fix, --fix ]
Expand Down
10 changes: 7 additions & 3 deletions asyncpraw/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import sys
from pathlib import Path
from threading import Lock
from typing import Any

from .exceptions import ClientException

Expand Down Expand Up @@ -44,6 +45,7 @@ def _load_config(cls, *, config_interpolation: str | None = None):
interpolator_class = cls.INTERPOLATION_LEVEL[config_interpolation]()
else:
interpolator_class = None

config = configparser.ConfigParser(interpolation=interpolator_class)
module_dir = Path(sys.modules[__name__].__file__).parent

Expand Down Expand Up @@ -96,17 +98,19 @@ def __init__(

self._initialize_attributes()

def _fetch(self, key): # noqa: ANN001
def _fetch(self, key: str) -> Any:
value = self.custom[key]
del self.custom[key]
return value

def _fetch_default(self, key, *, default=None): # noqa: ANN001
def _fetch_default(
self, key: str, *, default: bool | str | int | None = None
) -> Any:
if key not in self.custom:
return default
return self._fetch(key)

def _fetch_or_not_set(self, key): # noqa: ANN001
def _fetch_or_not_set(self, key: str) -> Any | _NotSet:
if key in self._settings: # Passed in values have the highest priority
return self._fetch(key)

Expand Down
1 change: 0 additions & 1 deletion asyncpraw/endpoints.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""List of API endpoints PRAW knows about."""
# flake8: noqa
# fmt: off
API_PATH = {
"about_edited": "r/{subreddit}/about/edited/",
Expand Down
6 changes: 3 additions & 3 deletions asyncpraw/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from .util import _deprecate_args


class AsyncPRAWException(Exception): # noqa: N818
class AsyncPRAWException(Exception):
"""The base Async PRAW Exception that all other exception classes extend."""


Expand All @@ -27,7 +27,7 @@ class AsyncPRAWException(Exception): # noqa: N818
class ExceptionWrapper:
"""Wrapper to facilitate showing depreciation for PRAWException class rename."""

def __getattr__(self, attribute): # noqa: ANN001,ANN204
def __getattr__(self, attribute: str) -> Any:
"""Return the value of `attribute`."""
if attribute == "PRAWException":
warn(
Expand Down Expand Up @@ -312,7 +312,7 @@ def __init__(
self.items = self.parse_exception_list(items)
super().__init__(*self.items)

def _get_old_attr(self, attrname): # noqa: ANN001
def _get_old_attr(self, attrname: str) -> Any:
warn(
f"Accessing attribute '{attrname}' through APIException is deprecated."
" This behavior will be removed in Async PRAW 8.0. Check out"
Expand Down
4 changes: 2 additions & 2 deletions asyncpraw/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class AsyncPRAWBase:

@staticmethod
def _safely_add_arguments(
*, arguments, key, **new_arguments # noqa: ANN001,ANN003,ANN205
*, arguments: dict[str, Any], key: str, **new_arguments: Any
):
"""Replace arguments[key] with a deepcopy and update.
Expand All @@ -27,7 +27,7 @@ def _safely_add_arguments(
arguments[key] = value

@classmethod
def parse(cls, data: dict[str, Any], reddit: asyncpraw.Reddit) -> Any:
def parse(cls, data: dict[str, Any], reddit: asyncpraw.Reddit) -> AsyncPRAWBase:
"""Return an instance of ``cls`` from ``data``.
:param data: The structured data.
Expand Down
12 changes: 8 additions & 4 deletions asyncpraw/models/comment_forest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ class CommentForest:
"""

@staticmethod
def _gather_more_comments(tree, *, parent_tree=None): # noqa: ANN001,ANN205
def _gather_more_comments(
tree: list[asyncpraw.models.MoreComments],
*,
parent_tree: list[asyncpraw.models.MoreComments] | None = None,
) -> list[MoreComments]:
"""Return a list of :class:`.MoreComments` objects obtained from tree."""
more_comments = []
queue = [(None, x) for x in tree]
Expand Down Expand Up @@ -60,7 +64,7 @@ async def __aiter__(self) -> AsyncIterator[asyncpraw.models.Comment]:
for comment in self:
yield comment

async def __call__(self): # noqa: ANN204
async def __call__(self) -> CommentForest:
"""Return the instance.
This method is deprecated and will be removed in a future version.
Expand Down Expand Up @@ -104,7 +108,7 @@ def __len__(self) -> int:
"""Return the number of top-level comments in the forest."""
return len(self._comments or [])

def _insert_comment(self, comment): # noqa: ANN001
def _insert_comment(self, comment: asyncpraw.models.Comment):
if comment.name in self._submission._comments_by_id:
raise DuplicateReplaceException
comment.submission = self._submission
Expand All @@ -118,7 +122,7 @@ def _insert_comment(self, comment): # noqa: ANN001
parent = self._submission._comments_by_id[comment.parent_id]
parent.replies._comments.append(comment)

def _update(self, comments): # noqa: ANN001
def _update(self, comments: list[asyncpraw.models.Comment]):
self._comments = comments
for comment in comments:
comment.submission = self._submission
Expand Down
6 changes: 3 additions & 3 deletions asyncpraw/models/listing/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class ListingGenerator(AsyncPRAWBase, AsyncIterator):
"""

def __aiter__(self): # noqa: ANN204
def __aiter__(self) -> Any:
"""Permit :class:`.ListingGenerator` to operate as an async iterator."""
return self

Expand Down Expand Up @@ -68,7 +68,7 @@ def __init__(
self.url = url
self.yielded = 0

def _extract_sublist(self, listing): # noqa: ANN001
def _extract_sublist(self, listing: dict[str, Any] | list[Any]):
if isinstance(listing, list):
return listing[1] # for submission duplicates
if isinstance(listing, dict):
Expand All @@ -82,7 +82,7 @@ def _extract_sublist(self, listing): # noqa: ANN001
raise ValueError(msg)
return listing

async def _next_batch(self): # noqa: ANN001
async def _next_batch(self):
if self._exhausted:
raise StopAsyncIteration

Expand Down
4 changes: 2 additions & 2 deletions asyncpraw/models/listing/mixins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class BaseListingMixin(AsyncPRAWBase):
VALID_TIME_FILTERS = {"all", "day", "hour", "month", "week", "year"}

@staticmethod
def _validate_time_filter(time_filter): # noqa: ANN001
def _validate_time_filter(time_filter: str):
"""Validate ``time_filter``.
:raises: :py:class:`ValueError` if ``time_filter`` is not valid.
Expand All @@ -28,7 +28,7 @@ def _validate_time_filter(time_filter): # noqa: ANN001
msg = f"'time_filter' must be one of: {valid_time_filters}"
raise ValueError(msg)

def _prepare(self, *, arguments, sort): # noqa: ANN001
def _prepare(self, *, arguments: dict[str, Any], sort: str) -> str:
"""Fix for :class:`.Redditor` methods that use a query param rather than subpath."""
if self.__dict__.get("_listing_use_sort"):
self._safely_add_arguments(arguments=arguments, key="params", sort=sort)
Expand Down
2 changes: 1 addition & 1 deletion asyncpraw/models/mod_notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ async def _bulk_generator(
for note_dict in response["mod_notes"]:
yield self._reddit._objector.objectify(note_dict)

def _ensure_attribute(self, error_message: str, **attributes: Any): # noqa: ANN001
def _ensure_attribute(self, error_message: str, **attributes: Any) -> Any:
attribute, _value = attributes.popitem()
value = _value or getattr(self, attribute, None)
if value is None:
Expand Down
6 changes: 3 additions & 3 deletions asyncpraw/models/reddit/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class RedditBase(AsyncPRAWBase):
"""Base class that represents actual Reddit objects."""

@staticmethod
def _url_parts(url): # noqa: ANN001,ANN205
def _url_parts(url: str) -> list[str]:
parsed = urlparse(url)
if not parsed.netloc:
raise InvalidURL(url)
Expand Down Expand Up @@ -84,12 +84,12 @@ def __str__(self) -> str:
async def _fetch(self): # pragma: no cover
self._fetched = True

async def _fetch_data(self): # noqa: ANN001
async def _fetch_data(self):
name, fields, params = self._fetch_info()
path = API_PATH[name].format(**fields)
return await self._reddit.request(method="GET", params=params, path=path)

def _reset_attributes(self, *attributes): # noqa: ANN001,ANN002
def _reset_attributes(self, *attributes: str):
for attribute in attributes:
if attribute in self.__dict__:
del self.__dict__[attribute]
Expand Down
4 changes: 2 additions & 2 deletions asyncpraw/models/reddit/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(self, reddit: asyncpraw.Reddit, collection_id: str):
super().__init__(reddit, _data=None)
self.collection_id = collection_id

def _post_fullname(self, post): # noqa: ANN001
def _post_fullname(self, post: str | asyncpraw.models.Submission) -> str:
"""Get a post's fullname.
:param post: A fullname, a :class:`.Submission`, a permalink, or an ID.
Expand Down Expand Up @@ -565,7 +565,7 @@ async def _fetch(self):

other = type(self)(self._reddit, _data=data)
self.__dict__.update(other.__dict__)
self._fetched = True
await super()._fetch()

def _fetch_info(self):
return "collection", {}, self._info_params
Expand Down
4 changes: 2 additions & 2 deletions asyncpraw/models/reddit/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def mod(self) -> asyncpraw.models.reddit.comment.CommentModeration:
return CommentModeration(self)

@property
def _kind(self): # noqa: ANN001
def _kind(self):
"""Return the class's kind."""
return self._reddit.config.kinds["comment"]

Expand Down Expand Up @@ -209,7 +209,7 @@ async def _fetch(self):
comment_data = data["children"][0]["data"]
other = type(self)(self._reddit, _data=comment_data)
self.__dict__.update(other.__dict__)
self._fetched = True
await super()._fetch()

def _fetch_info(self):
return "info", {}, {"id": self.fullname}
Expand Down
2 changes: 1 addition & 1 deletion asyncpraw/models/reddit/draft.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ async def _fetch(self):
async for draft in self._reddit.drafts:
if draft.id == self.id:
self.__dict__.update(draft.__dict__)
self._fetched = True
await super()._fetch()
return
msg = (
f"The currently authenticated user not have a draft with an ID of {self.id}"
Expand Down
8 changes: 3 additions & 5 deletions asyncpraw/models/reddit/emoji.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ def __init__(
self.subreddit = subreddit
super().__init__(reddit, _data=_data)

async def _fetch(self): # noqa: ANN001
async def _fetch(self):
async for emoji in self.subreddit.emoji:
if emoji.name == self.name:
self.__dict__.update(emoji.__dict__)
self._fetched = True
await super()._fetch()
return
msg = f"r/{self.subreddit} does not have the emoji {self.name}"
raise ClientException(msg)
Expand Down Expand Up @@ -239,9 +239,7 @@ async def add(
return Emoji(self._reddit, self.subreddit, name)

@deprecate_lazy
async def get_emoji(
self, name: str, fetch: bool = True, **kwargs: Any # noqa: ARG002
) -> Emoji:
async def get_emoji(self, name: str, fetch: bool = True, **_: Any) -> Emoji:
"""Return the :class:`.Emoji` for the subreddit named ``name``.
:param name: The name of the emoji.
Expand Down
10 changes: 5 additions & 5 deletions asyncpraw/models/reddit/live.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Provide the LiveThread class."""
from __future__ import annotations

from typing import TYPE_CHECKING, Any, AsyncIterator
from typing import TYPE_CHECKING, Any, AsyncIterator, Iterable

from ...const import API_PATH
from ...util import _deprecate_args
Expand All @@ -21,7 +21,7 @@ class LiveContributorRelationship:
"""Provide methods to interact with live threads' contributors."""

@staticmethod
def _handle_permissions(permissions): # noqa: ANN001,ANN205
def _handle_permissions(permissions: Iterable[str]) -> str:
permissions = {"all"} if permissions is None else set(permissions)
return ",".join(f"+{x}" for x in permissions)

Expand Down Expand Up @@ -384,7 +384,7 @@ async def _fetch(self):
data = data["data"]
other = type(self)(self._reddit, _data=data)
self.__dict__.update(other.__dict__)
self._fetched = True
await super()._fetch()

def _fetch_info(self):
return "liveabout", {"id": self.id}, None
Expand Down Expand Up @@ -417,7 +417,7 @@ def discussions(

@deprecate_lazy
async def get_update(
self, update_id: str, fetch: bool = True, **kwargs: Any # noqa: ARG002
self, update_id: str, fetch: bool = True, **_: Any
) -> asyncpraw.models.LiveUpdate:
"""Return a :class:`.LiveUpdate` instance.
Expand Down Expand Up @@ -826,4 +826,4 @@ async def _fetch(self):
response = await self._reddit.get(url)
other = response[0]
self.__dict__.update(other.__dict__)
self._fetched = True
await super()._fetch()
2 changes: 1 addition & 1 deletion asyncpraw/models/reddit/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def __init__(self, reddit: asyncpraw.Reddit, _data: dict[str, Any]):
async def _fetch(self):
message = await self._reddit.inbox.message(self.id)
self.__dict__.update(message.__dict__)
self._fetched = True
await super()._fetch()

async def delete(self):
"""Delete the message.
Expand Down
2 changes: 1 addition & 1 deletion asyncpraw/models/reddit/mixins/votable.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class VotableMixin:
"""Interface for :class:`.RedditBase` classes that can be voted on."""

async def _vote(self, direction): # noqa: ANN001
async def _vote(self, direction: int):
await self._reddit.post(
API_PATH["vote"], data={"dir": str(direction), "id": self.fullname}
)
Expand Down
Loading

0 comments on commit cd63b50

Please sign in to comment.