Skip to content

Commit

Permalink
ruff: enable unused local variables detection (F841) and clean up mod…
Browse files Browse the repository at this point in the history
…ules
  • Loading branch information
karlicoss committed Feb 3, 2025
1 parent e4381d6 commit db46380
Show file tree
Hide file tree
Showing 13 changed files with 26 additions and 38 deletions.
6 changes: 0 additions & 6 deletions ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,6 @@ lint.ignore = [
## might be nice .. but later and I don't wanna make it strict
"E402", # Module level import not at top of file

### maybe consider these soon
# sometimes it's useful to give a variable a name even if we don't use it as a documentation
# on the other hand, often is a sign of error
"F841", # Local variable `count` is assigned to but never used
###

"RUF100", # unused noqa -- handle later
"RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs

Expand Down
6 changes: 2 additions & 4 deletions src/my/bluemaestro.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def measurements() -> Iterable[Res[Measurement]]:
processed_tables |= set(log_tables)

# todo use later?
frequencies = [list(db.execute(f'SELECT interval from {t.replace("_log", "_meta")}'))[0][0] for t in log_tables] # noqa: RUF015
_frequencies = [list(db.execute(f'SELECT interval from {t.replace("_log", "_meta")}'))[0][0] for t in log_tables] # noqa: RUF015

# todo could just filter out the older datapoints?? dunno.

Expand Down Expand Up @@ -177,7 +177,7 @@ def measurements() -> Iterable[Res[Measurement]]:
# not sure how that happens.. but basically they'd better be excluded
lower = timedelta(days=6000 / 24) # ugh some time ago I only did it once in an hour.. in theory can detect from meta?
upper = timedelta(days=10) # kinda arbitrary
if not (db_dt - lower < dt < db_dt + timedelta(days=10)):
if not (db_dt - lower < dt < db_dt + upper):
# todo could be more defenive??
yield RuntimeError('timestamp too far out', path, name, db_dt, dt)
continue
Expand Down Expand Up @@ -252,10 +252,8 @@ def check() -> None:

POINTS_STORED = 6000 # on device?
FREQ_SEC = 60
SECS_STORED = POINTS_STORED * FREQ_SEC
HOURS_STORED = POINTS_STORED / (60 * 60 / FREQ_SEC) # around 4 days
NOW = datetime.now()
assert NOW - last < timedelta(hours=HOURS_STORED / 2), f'old backup! {last}'

assert last - prev < timedelta(minutes=3), f'bad interval! {last - prev}'
single = (last - prev).seconds
2 changes: 1 addition & 1 deletion src/my/body/weight.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def from_orgmode() -> Iterator[Result]:
cfg = make_config()

orgs = orgmode.query()
for o in orgmode.query().all():
for o in orgs.all():
if 'weight' not in o.tags:
continue
try:
Expand Down
4 changes: 2 additions & 2 deletions src/my/core/core_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@

try:
from my.config import core as user_config # type: ignore[attr-defined]
except Exception as e:
except Exception as _e:
try:
from my.config import common as user_config # type: ignore[attr-defined]

warnings.high("'common' config section is deprecated. Please rename it to 'core'.")
except Exception as e2:
except Exception as _e2:
# make it defensive, because it's pretty commonly used and would be annoying if it breaks hpi doctor etc.
# this way it'll at least use the defaults
# todo actually not sure if needs a warning? Perhaps it's okay without it, because the defaults are reasonable enough
Expand Down
18 changes: 6 additions & 12 deletions src/my/core/konsume.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
from __future__ import annotations

from collections import OrderedDict
from typing import Any
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any, cast


def ignore(w, *keys):
Expand Down Expand Up @@ -125,10 +127,6 @@ def _wrap(j, parent=None) -> tuple[Zoomable, list[Zoomable]]:
raise RuntimeError(f'Unexpected type: {type(j)} {j}')


from collections.abc import Iterator
from contextlib import contextmanager


class UnconsumedError(Exception):
pass

Expand All @@ -152,32 +150,28 @@ def wrap(j, *, throw=True) -> Iterator[Zoomable]:
pass


from typing import cast


def test_unconsumed() -> None:
import pytest

with pytest.raises(UnconsumedError):
with wrap({'a': 1234}) as w:
w = cast(Wdict, w)
pass

with pytest.raises(UnconsumedError):
with wrap({'c': {'d': 2222}}) as w:
w = cast(Wdict, w)
d = w['c']['d'].zoom()
_d = w['c']['d'].zoom()


def test_consumed() -> None:
with wrap({'a': 1234}) as w:
w = cast(Wdict, w)
a = w['a'].zoom()
_a = w['a'].zoom()

with wrap({'c': {'d': 2222}}) as w:
w = cast(Wdict, w)
c = w['c'].zoom()
d = c['d'].zoom()
_d = c['d'].zoom()


def test_types() -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/my/core/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def is_not_hpi_module(module: str) -> str | None:
spec = importlib.util.find_spec(module)
assert spec is not None
path = spec.origin
except Exception as e:
except Exception:
# todo a bit misleading.. it actually shouldn't import in most cases, it's just the weird parent module import thing
return "import error (possibly missing config entry)" # todo add exc message?
assert path is not None # not sure if can happen?
Expand Down
6 changes: 3 additions & 3 deletions src/my/core/utils/itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ def test_make_dict() -> None:
d = make_dict(it, key=lambda i: i % 2, value=lambda i: i)

# check type inference
d2: dict[str, int] = make_dict(it, key=lambda i: str(i))
d3: dict[str, bool] = make_dict(it, key=lambda i: str(i), value=lambda i: i % 2 == 0)
_d2: dict[str, int] = make_dict(it, key=lambda i: str(i))
_d3: dict[str, bool] = make_dict(it, key=lambda i: str(i), value=lambda i: i % 2 == 0)


LFP = ParamSpec('LFP')
Expand Down Expand Up @@ -286,7 +286,7 @@ def test_check_if_hashable() -> None:
x4: list[set[int]] = [{1, 2, 3}, {4, 5, 6}]
with pytest.raises(Exception):
# should be rejected by mypy sice set isn't Hashable, but also throw at runtime
r4 = check_if_hashable(x4) # type: ignore[type-var]
_r4 = check_if_hashable(x4) # type: ignore[type-var]

x5: Iterator[object] = iter([{1, 2}, {3, 4}])
# here, we hide behind object, which is hashable
Expand Down
2 changes: 1 addition & 1 deletion src/my/google/maps/_android_protobuf.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def make_parser(main, *extras):
file_descriptor_proto.message_type.add().CopyFrom(proto)

pool = descriptor_pool.DescriptorPool()
file_descriptor = pool.Add(file_descriptor_proto)
_file_descriptor = pool.Add(file_descriptor_proto)

message_descriptor = pool.FindMessageTypeByName(f'{file_descriptor_proto.package}.{main.name}')
factory = message_factory.MessageFactory(pool)
Expand Down
2 changes: 1 addition & 1 deletion src/my/location/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def _iter_locations_fo(fit) -> Iterable[Location]:
lat = float(latE7 / 1e7)
lon = float(lonE7 / 1e7)
# note: geopy is quite slow..
point = geopy.Point(lat, lon) # kinda sanity check that coordinates are ok
_point = geopy.Point(lat, lon) # kinda sanity check that coordinates are ok
except Exception as e:
logger.exception(e)
errors += 1
Expand Down
2 changes: 1 addition & 1 deletion src/my/orgmode.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def to_note(x: orgparse.OrgNode) -> OrgNote:
else:
# meh. not sure if should return date...
created = None
except Exception as e:
except Exception:
created = None
return OrgNote(
created=created,
Expand Down
10 changes: 6 additions & 4 deletions src/my/polar.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,11 @@ def load_item(self, meta: Zoomable) -> Iterable[Highlight]:

if 'notes' in meta:
# TODO something nicer?
notes = meta['notes'].zoom()
_notes = meta['notes'].zoom()
else:
notes = []
_notes = []
# not sure what is 'notes', seemed always empty for me?

comments = list(meta['comments'].zoom().values()) if 'comments' in meta else []
meta['questions'].zoom()
meta['flashcards'].zoom()
Expand All @@ -141,7 +143,7 @@ def load_item(self, meta: Zoomable) -> Iterable[Highlight]:
v['guid'].zoom()
# TODO values should probably be checked by flow analysis??
crt = v['created'].zoom()
updated = v['lastUpdated'].zoom()
_updated = v['lastUpdated'].zoom()
content = v['content'].zoom()
html = content['HTML'].zoom()
refv = v['ref'].zoom().value
Expand All @@ -164,7 +166,7 @@ def load_item(self, meta: Zoomable) -> Iterable[Highlight]:

h['guid'].consume()
crt = h['created'].zoom().value
updated = h['lastUpdated'].zoom().value
_updated = h['lastUpdated'].zoom().value
h['rects'].ignore()

# TODO make it more generic..
Expand Down
2 changes: 1 addition & 1 deletion src/my/tests/commits.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test() -> None:
assert len(all_commits) > 100

buckets = bucket(all_commits, key=lambda c: c.repo)
by_repo = {k: list(buckets[k]) for k in buckets}
_by_repo = {k: list(buckets[k]) for k in buckets}
# handle later


Expand Down
2 changes: 1 addition & 1 deletion src/my/time/tz/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def default_policy() -> TzPolicy:
try:
from my.config import time as user_config
return cast(TzPolicy, user_config.tz.policy)
except Exception as e:
except Exception as _e:
# todo meh.. need to think how to do this more carefully
# rationale: do not mess with user's data unless they want
return 'keep'
Expand Down

0 comments on commit db46380

Please sign in to comment.