Skip to content

Commit fb3583a

Browse files
committed
ci: update ruff rules
1 parent 06cf9f2 commit fb3583a

File tree

12 files changed

+109
-119
lines changed

12 files changed

+109
-119
lines changed

ruff.toml

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ lint.extend-select = [
2828
"PTH", # pathlib migration
2929
# "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later
3030
"A", # builtin shadowing
31+
"G", # logging stuff
3132
# "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying
3233

3334
# "ALL", # uncomment this to check for new rules!
@@ -64,14 +65,8 @@ lint.ignore = [
6465
# sometimes it's useful to give a variable a name even if we don't use it as a documentation
6566
# on the other hand, often is a sign of error
6667
"F841", # Local variable `count` is assigned to but never used
67-
"F401", # imported but unused
6868
###
6969

70-
### TODO should be fine to use these with from __future__ import annotations?
71-
### there was some issue with cachew though... double check this?
72-
"UP006", # use type instead of Type
73-
"UP007", # use X | Y instead of Union
74-
###
7570
"RUF100", # unused noqa -- handle later
7671
"RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs
7772

@@ -112,7 +107,6 @@ lint.ignore = [
112107
"PLW0603", # global variable update.. we usually know why we are doing this
113108
"PLW2901", # for loop variable overwritten, usually this is intentional
114109

115-
"PT004", # deprecated rule, will be removed later
116110
"PT011", # pytest raises should is too broad
117111
"PT012", # pytest raises should contain a single statement
118112

src/cachew/__init__.py

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,16 @@
88
import stat
99
import sys
1010
import warnings
11+
from collections.abc import Iterable
1112
from dataclasses import dataclass
1213
from pathlib import Path
1314
from typing import (
1415
TYPE_CHECKING,
1516
Any,
1617
Callable,
17-
Dict,
1818
Generic,
19-
Iterable,
20-
List,
2119
Literal,
2220
Optional,
23-
Tuple,
24-
Type,
2521
TypeVar,
2622
Union,
2723
cast,
@@ -89,7 +85,7 @@ def get_logger() -> logging.Logger:
8985
return make_logger(__name__)
9086

9187

92-
BACKENDS: Dict[Backend, Type[AbstractBackend]] = {
88+
BACKENDS: dict[Backend, type[AbstractBackend]] = {
9389
'file': FileBackend,
9490
'sqlite': SqliteBackend,
9591
}
@@ -130,7 +126,7 @@ def mtime_hash(path: Path, *args, **kwargs) -> SourceHash:
130126

131127
Failure = str
132128
Kind = Literal['single', 'multiple']
133-
Inferred = Tuple[Kind, Type[Any]]
129+
Inferred = tuple[Kind, type[Any]]
134130

135131

136132
def infer_return_type(func) -> Union[Failure, Inferred]:
@@ -299,7 +295,7 @@ def cachew_impl(
299295
cache_path: Optional[PathProvider[P]] = use_default_path,
300296
*,
301297
force_file: bool = False,
302-
cls: Optional[Union[Type, Tuple[Kind, Type]]] = None,
298+
cls: Optional[Union[type, tuple[Kind, type]]] = None,
303299
depends_on: HashFunction[P] = default_hash,
304300
logger: Optional[logging.Logger] = None,
305301
chunk_by: int = 100,
@@ -387,7 +383,7 @@ def process(self, msg, kwargs):
387383
logger.debug(f'no cache_path specified, using the default {cache_path}')
388384

389385
use_kind: Optional[Kind] = None
390-
use_cls: Optional[Type] = None
386+
use_cls: Optional[type] = None
391387
if cls is not None:
392388
# defensive here since typing. objects passed as cls might fail on isinstance
393389
try:
@@ -475,7 +471,7 @@ def cachew(
475471
cache_path: Optional[PathProvider[P]] = ...,
476472
*,
477473
force_file: bool = ...,
478-
cls: Optional[Union[Type, Tuple[Kind, Type]]] = ...,
474+
cls: Optional[Union[type, tuple[Kind, type]]] = ...,
479475
depends_on: HashFunction[P] = ...,
480476
logger: Optional[logging.Logger] = ...,
481477
chunk_by: int = ...,
@@ -498,7 +494,7 @@ def callable_module_name(func: Callable) -> Optional[str]:
498494

499495

500496
# could cache this, but might be worth not to, so the user can change it on the fly?
501-
def _parse_disabled_modules(logger: Optional[logging.Logger] = None) -> List[str]:
497+
def _parse_disabled_modules(logger: Optional[logging.Logger] = None) -> list[str]:
502498
# e.g. CACHEW_DISABLE=my.browser:my.reddit
503499
if 'CACHEW_DISABLE' not in os.environ:
504500
return []
@@ -582,14 +578,14 @@ class Context(Generic[P]):
582578
func : Callable
583579
cache_path : PathProvider[P]
584580
force_file : bool
585-
cls_ : Type
581+
cls_ : type
586582
depends_on : HashFunction[P]
587583
logger : logging.Logger
588584
chunk_by : int
589585
synthetic_key: Optional[str]
590586
backend : Optional[Backend]
591587

592-
def composite_hash(self, *args, **kwargs) -> Dict[str, Any]:
588+
def composite_hash(self, *args, **kwargs) -> dict[str, Any]:
593589
fsig = inspect.signature(self.func)
594590
# defaults wouldn't be passed in kwargs, but they can be an implicit dependency (especially inbetween program runs)
595591
defaults = {
@@ -693,7 +689,7 @@ def try_use_synthetic_key() -> None:
693689
return
694690
# attempt to use existing cache if possible, as a 'prefix'
695691

696-
old_hash_d: Dict[str, Any] = {}
692+
old_hash_d: dict[str, Any] = {}
697693
if old_hash is not None:
698694
try:
699695
old_hash_d = json.loads(old_hash)
@@ -711,7 +707,7 @@ def try_use_synthetic_key() -> None:
711707
if not cache_compatible:
712708
return
713709

714-
def missing_keys(cached: List[str], wanted: List[str]) -> Optional[List[str]]:
710+
def missing_keys(cached: list[str], wanted: list[str]) -> Optional[list[str]]:
715711
# FIXME assert both cached and wanted are sorted? since we rely on it
716712
# if not, then the user could use some custom key for caching (e.g. normalise filenames etc)
717713
# although in this case passing it into the function wouldn't make sense?
@@ -734,8 +730,8 @@ def missing_keys(cached: List[str], wanted: List[str]) -> Optional[List[str]]:
734730
# otherwise too many things are cached, and we seem to wante less
735731
return None
736732

737-
new_values: List[str] = new_hash_d[_SYNTHETIC_KEY_VALUE]
738-
old_values: List[str] = old_hash_d[_SYNTHETIC_KEY_VALUE]
733+
new_values: list[str] = new_hash_d[_SYNTHETIC_KEY_VALUE]
734+
old_values: list[str] = old_hash_d[_SYNTHETIC_KEY_VALUE]
739735
missing = missing_keys(cached=old_values, wanted=new_values)
740736
if missing is not None:
741737
# can reuse cache
@@ -760,7 +756,7 @@ def written_to_cache():
760756

761757
flush_blobs = backend.flush_blobs
762758

763-
chunk: List[Any] = []
759+
chunk: list[Any] = []
764760

765761
def flush() -> None:
766762
nonlocal chunk
@@ -849,9 +845,9 @@ def cached_items():
849845

850846

851847
__all__ = [
852-
'cachew',
853848
'CachewException',
854-
'SourceHash',
855849
'HashFunction',
850+
'SourceHash',
851+
'cachew',
856852
'get_logger',
857853
]

src/cachew/backend/common.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import logging
22
from abc import abstractmethod
3+
from collections.abc import Iterator, Sequence
34
from pathlib import Path
45
from typing import (
5-
Iterator,
66
Optional,
7-
Sequence,
87
)
98

109
from ..common import SourceHash

src/cachew/backend/file.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import logging
2-
import os
2+
from collections.abc import Iterator, Sequence
33
from pathlib import Path
44
from typing import (
55
BinaryIO,
6-
Iterator,
76
Optional,
8-
Sequence,
97
)
108

119
from ..common import SourceHash

src/cachew/backend/sqlite.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,10 @@
22
import sqlite3
33
import time
44
import warnings
5+
from collections.abc import Iterator, Sequence
56
from pathlib import Path
67
from typing import (
7-
Iterator,
88
Optional,
9-
Sequence,
109
)
1110

1211
import sqlalchemy

src/cachew/legacy.py

Lines changed: 23 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,15 @@
11
import typing
22
import warnings
3+
from collections.abc import Iterable, Iterator, Sequence
34
from dataclasses import dataclass
45
from datetime import date, datetime
56
from itertools import chain, islice
67
from pathlib import Path
78
from typing import (
89
Any,
910
Generic,
10-
Iterable,
11-
Iterator,
12-
List,
1311
NamedTuple,
1412
Optional,
15-
Sequence,
16-
Set,
17-
Tuple,
18-
Type,
1913
TypeVar,
2014
Union,
2115
)
@@ -27,7 +21,7 @@
2721
from .utils import CachewException
2822

2923

30-
def get_union_args(cls) -> Optional[Tuple[Type]]:
24+
def get_union_args(cls) -> Optional[tuple[type]]:
3125
if getattr(cls, '__origin__', None) != Union:
3226
return None
3327

@@ -42,16 +36,16 @@ def is_union(cls) -> bool:
4236

4337

4438
Types = Union[
45-
Type[str],
46-
Type[int],
47-
Type[float],
48-
Type[bool],
49-
Type[datetime],
50-
Type[date],
51-
Type[dict],
52-
Type[list],
53-
Type[Exception],
54-
Type[NamedTuple],
39+
type[str],
40+
type[int],
41+
type[float],
42+
type[bool],
43+
type[datetime],
44+
type[date],
45+
type[dict],
46+
type[list],
47+
type[Exception],
48+
type[NamedTuple],
5549
]
5650

5751
Values = Union[
@@ -80,7 +74,7 @@ def is_union(cls) -> bool:
8074
}
8175

8276

83-
def is_primitive(cls: Type) -> bool:
77+
def is_primitive(cls: type) -> bool:
8478
"""
8579
>>> from typing import Dict, Any
8680
>>> is_primitive(int)
@@ -194,10 +188,10 @@ def python_type(self):
194188
def process_literal_param(self, value, dialect):
195189
raise NotImplementedError() # make pylint happy
196190

197-
def process_bind_param(self, value: Optional[Exception], dialect) -> Optional[List[Any]]:
191+
def process_bind_param(self, value: Optional[Exception], dialect) -> Optional[list[Any]]:
198192
if value is None:
199193
return None
200-
sargs: List[Any] = []
194+
sargs: list[Any] = []
201195
for a in value.args:
202196
if any(isinstance(a, t) for t in jtypes):
203197
sargs.append(a)
@@ -230,7 +224,7 @@ def process_result_value(self, value: Optional[str], dialect) -> Optional[Except
230224
assert set(PRIMITIVES.keys()) == PRIMITIVE_TYPES
231225

232226

233-
def strip_optional(cls) -> Tuple[Type, bool]:
227+
def strip_optional(cls) -> tuple[type, bool]:
234228
"""
235229
>>> from typing import Optional, NamedTuple
236230
>>> strip_optional(Optional[int])
@@ -313,14 +307,14 @@ class NTBinder(Generic[NT]):
313307
span: int # not sure if span should include optional col?
314308
primitive: bool
315309
optional: bool
316-
union: Optional[Type] # helper, which isn't None if type is Union
310+
union: Optional[type] # helper, which isn't None if type is Union
317311
fields: Sequence[Any] # mypy can't handle cyclic definition at this point :(
318312

319313
@staticmethod
320-
def make(tp: Type[NT], name: Optional[str] = None) -> 'NTBinder[NT]':
314+
def make(tp: type[NT], name: Optional[str] = None) -> 'NTBinder[NT]':
321315
tp, optional = strip_optional(tp)
322-
union: Optional[Type]
323-
fields: Tuple[Any, ...]
316+
union: Optional[type]
317+
fields: tuple[Any, ...]
324318
primitive: bool
325319

326320
union_args = get_union_args(tp)
@@ -360,11 +354,11 @@ def make(tp: Type[NT], name: Optional[str] = None) -> 'NTBinder[NT]':
360354
)
361355

362356
@property
363-
def columns(self) -> List[Column]:
357+
def columns(self) -> list[Column]:
364358
return list(self.iter_columns())
365359

366360
# TODO not necessarily namedtuple? could be primitive type
367-
def to_row(self, obj: NT) -> Tuple[Optional[Values], ...]:
361+
def to_row(self, obj: NT) -> tuple[Optional[Values], ...]:
368362
return tuple(self._to_row(obj))
369363

370364
def from_row(self, row: Iterable[Any]) -> NT:
@@ -425,7 +419,7 @@ def _from_row(self, row_iter):
425419

426420
# TODO not sure if we want to allow optionals on top level?
427421
def iter_columns(self) -> Iterator[Column]:
428-
used_names: Set[str] = set()
422+
used_names: set[str] = set()
429423

430424
def col(name: str, tp) -> Column:
431425
while name in used_names:

0 commit comments

Comments
 (0)