Skip to content

Commit

Permalink
Use typing.Self where possible. #287
Browse files Browse the repository at this point in the history
  • Loading branch information
lemon24 committed Oct 29, 2023
1 parent 71b6cfc commit 34f23cd
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 35 deletions.
4 changes: 2 additions & 2 deletions src/reader/_parser/requests/_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from . import TimeoutType

if TYPE_CHECKING: # pragma: no cover
from typing_extensions import Self
from . import Headers
from . import RequestHook
from . import ResponseHook
Expand Down Expand Up @@ -136,8 +137,7 @@ def caching_get(

return response, etag, last_modified

def __enter__(self: _T) -> _T:
# TODO: use typing.Self instead of _T
def __enter__(self) -> Self:
return self

def __exit__(self, *args: Any) -> None:
Expand Down
15 changes: 9 additions & 6 deletions src/reader/_sql_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@
from typing import TypeVar
from typing import Union

if TYPE_CHECKING: # pragma: no cover
from typing_extensions import Self


_T = TypeVar('_T')
_U = TypeVar('_U')


_Q = TypeVar('_Q', bound='BaseQuery')
_QArg = Union[str, tuple[str, ...]]


Expand Down Expand Up @@ -108,7 +111,7 @@ def __init__(
if separators is not None:
self.separators = separators

def add(self: _Q, keyword: str, *args: _QArg) -> _Q:
def add(self, keyword: str, *args: _QArg) -> Self:
keyword, fake_keyword = self._resolve_fakes(keyword)
keyword, flag = self._resolve_flags(keyword)
target = self.data[keyword]
Expand Down Expand Up @@ -143,7 +146,7 @@ def _resolve_flags(self, keyword: str) -> tuple[str, str]:
return prefix, flag
return keyword, ''

def __getattr__(self: _Q, name: str) -> Callable[..., _Q]:
def __getattr__(self, name: str) -> Callable[..., Self]:
# conveniently, avoids shadowing dunder methods (e.g. __deepcopy__)
if not name.isupper():
return getattr(super(), name) # type: ignore
Expand Down Expand Up @@ -206,8 +209,8 @@ def __init__(self, *args: Any, **kwargs: Any):
self.scrolling_window_order_by()

def scrolling_window_order_by(
self: _SWM, *things: str, desc: bool = False, keyword: str = 'WHERE'
) -> _SWM:
self, *things: str, desc: bool = False, keyword: str = 'WHERE'
) -> Self:
self.__things = [_clean_up(t) for t in things]
self.__desc = desc
self.__keyword = keyword
Expand All @@ -225,7 +228,7 @@ def add_last(self, last: tuple[_T, ...] | None) -> list[tuple[str, _T]]:

__make_label = 'last_{}'.format

def __add_last(self: _SWM) -> None:
def __add_last(self) -> None:
op = '<' if self.__desc else '>'
labels = (':' + self.__make_label(i) for i in range(len(self.__things)))
comparison = BaseQuery({'(': self.__things, f') {op} (': labels, ')': ['']})
Expand Down
21 changes: 10 additions & 11 deletions src/reader/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from typing import NamedTuple
from typing import overload
from typing import Protocol
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union

Expand Down Expand Up @@ -49,6 +50,10 @@
from .types import TagFilterInput
from .types import TristateFilterInput

if TYPE_CHECKING: # pragma: no cover
from typing_extensions import Self


log = logging.getLogger("reader")

# Private API
Expand Down Expand Up @@ -434,9 +439,6 @@ def tristate_filter_argument(value: TristateFilterInput, name: str) -> TristateF
raise ValueError(f"{name} must be none, bool, or one of {args}")


_EFO = TypeVar('_EFO', bound='EntryFilter')


class EntryFilter(NamedTuple):

"""Options for filtering the results of the "get entry" storage methods."""
Expand All @@ -450,14 +452,14 @@ class EntryFilter(NamedTuple):

@classmethod
def from_args(
cls: type[_EFO],
cls,
feed: FeedInput | None = None,
entry: EntryInput | None = None,
read: bool | None = None,
important: TristateFilterInput = None,
has_enclosures: bool | None = None,
feed_tags: TagFilterInput = None,
) -> _EFO:
) -> Self:
feed_url = _feed_argument(feed) if feed is not None else None

# TODO: should we allow specifying both feed and entry?
Expand All @@ -480,9 +482,6 @@ def from_args(
)


_FFO = TypeVar('_FFO', bound='FeedFilter')


class FeedFilter(NamedTuple):

"""Options for filtering the results of the "get feed" storage methods."""
Expand All @@ -495,13 +494,13 @@ class FeedFilter(NamedTuple):

@classmethod
def from_args(
cls: type[_FFO],
cls,
feed: FeedInput | None = None,
tags: TagFilterInput = None,
broken: bool | None = None,
updates_enabled: bool | None = None,
new: bool | None = None,
) -> _FFO:
) -> Self:
feed_url = _feed_argument(feed) if feed is not None else None
tag_filter = tag_filter_argument(tags)

Expand All @@ -522,7 +521,7 @@ class NameScheme(_namedtuple_compat):
separator: str

@classmethod
def from_value(cls, value: Mapping[str, str]) -> NameScheme:
def from_value(cls, value: Mapping[str, str]) -> Self:
# Use is validation.
self = cls(**value)
self.make_reader_name('key')
Expand Down
5 changes: 2 additions & 3 deletions src/reader/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
from .types import UpdateResult

if TYPE_CHECKING: # pragma: no cover
from typing_extensions import Self
from ._parser import Parser


Expand All @@ -86,8 +87,6 @@

_T = TypeVar('_T')
_U = TypeVar('_U')
# mypy doesn't seem to support Self yet.
_TReader = TypeVar('_TReader', bound='Reader')

AfterEntryUpdateHook = Callable[['Reader', EntryData, EntryUpdateStatus], None]
FeedUpdateHook = Callable[['Reader', str], None]
Expand Down Expand Up @@ -384,7 +383,7 @@ def __init__(
stacklevel=2,
)

def __enter__(self: _TReader) -> _TReader:
def __enter__(self) -> Self:
self._storage.__enter__()
return self

Expand Down
20 changes: 7 additions & 13 deletions src/reader/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from typing import overload
from typing import Protocol
from typing import runtime_checkable
from typing import TypeVar
from typing import TYPE_CHECKING
from typing import Union

from reader.exceptions import UpdateError
Expand All @@ -29,8 +29,8 @@
from reader._utils import MISSING as MISSING # noqa: F401
from reader._utils import MissingType as MissingType # noqa: F401


_T = TypeVar('_T')
if TYPE_CHECKING: # pragma: no cover
from typing_extensions import Self


class _namedtuple_compat:
Expand All @@ -40,7 +40,7 @@ class _namedtuple_compat:
# TODO: can we get rid of _namedtuple_compat?

@classmethod
def _make(cls: type[_T], iterable: Iterable[Any]) -> _T:
def _make(cls, iterable: Iterable[Any]) -> Self:
iterable = tuple(iterable)
attrs_len = len(dataclasses.fields(cls)) # type: ignore[arg-type]
if len(iterable) != attrs_len:
Expand All @@ -49,7 +49,7 @@ def _make(cls: type[_T], iterable: Iterable[Any]) -> _T:
)
return cls(*iterable)

def _replace(self: _T, **kargs: Any) -> _T:
def _replace(self, **kargs: Any) -> Self:
return dataclasses.replace(self, **kargs) # type: ignore[type-var,misc]

def _asdict(self) -> dict[str, Any]:
Expand Down Expand Up @@ -162,9 +162,6 @@ def resource_id(self) -> tuple[str]:
return (self.url,)


_EI = TypeVar('_EI', bound='ExceptionInfo')


@dataclass(frozen=True)
class ExceptionInfo(_namedtuple_compat):

Expand All @@ -187,7 +184,7 @@ class ExceptionInfo(_namedtuple_compat):
traceback_str: str

@classmethod
def from_exception(cls: type[_EI], exc: BaseException) -> _EI:
def from_exception(cls, exc: BaseException) -> Self:
return cls(
f'{type(exc).__module__}.{type(exc).__qualname__}',
str(exc),
Expand Down Expand Up @@ -430,9 +427,6 @@ class Enclosure(_namedtuple_compat):
length: int | None = None


_HS = TypeVar('_HS', bound='HighlightedString')


@dataclass(frozen=True)
class HighlightedString:

Expand Down Expand Up @@ -486,7 +480,7 @@ def __str__(self) -> str:
return self.value

@classmethod
def extract(cls: type[_HS], text: str, before: str, after: str) -> _HS:
def extract(cls, text: str, before: str, after: str) -> Self:
"""Extract highlights with before/after markers from text.
>>> HighlightedString.extract( '>one< two', '>', '<')
Expand Down

0 comments on commit 34f23cd

Please sign in to comment.