From 675bb66e524ddc920ff78c773ecdd1d33712d0c2 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 19 Aug 2024 01:08:10 +0100 Subject: [PATCH 01/55] some notes on rethinking mixning in the user config --- doc/experiments_with_config/run | 12 +++ doc/experiments_with_config/src/pkg/config.py | 74 +++++++++++++++++++ .../src/pkg/current_impl.py | 29 ++++++++ doc/experiments_with_config/src/pkg/py.typed | 0 .../src/pkg/via_dataclass.py | 38 ++++++++++ .../src/pkg/via_properties.py | 38 ++++++++++ my/whatsapp/android.py | 26 +++++-- 7 files changed, 211 insertions(+), 6 deletions(-) create mode 100755 doc/experiments_with_config/run create mode 100644 doc/experiments_with_config/src/pkg/config.py create mode 100644 doc/experiments_with_config/src/pkg/current_impl.py create mode 100644 doc/experiments_with_config/src/pkg/py.typed create mode 100644 doc/experiments_with_config/src/pkg/via_dataclass.py create mode 100644 doc/experiments_with_config/src/pkg/via_properties.py diff --git a/doc/experiments_with_config/run b/doc/experiments_with_config/run new file mode 100755 index 0000000..8e77e8a --- /dev/null +++ b/doc/experiments_with_config/run @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +cd "$(dirname "0")" + +WHAT="$1" + +export PYTHONPATH=src + +ERROR=0 +python3 -m mypy -p "pkg.$WHAT" || ERROR=1 +python3 -c "import pkg.$WHAT as M; M.run()" || ERROR=1 +exit "$ERROR" diff --git a/doc/experiments_with_config/src/pkg/config.py b/doc/experiments_with_config/src/pkg/config.py new file mode 100644 index 0000000..8bc30e2 --- /dev/null +++ b/doc/experiments_with_config/src/pkg/config.py @@ -0,0 +1,74 @@ +from dataclasses import dataclass + + +# 'bare' config, no typing annotations even +# current_impl : works both mypy and runtime +# if we comment out export_path, mypy DOES NOT fail (bad!) +# via_dataclass : FAILS both mypy and runtime +# via_properties: works both mypy and runtime +# if we comment out export_path, mypy fails (good!) +# src/pkg/via_properties.py:32:12:32:28: error: Cannot instantiate abstract class "combined_config" with abstract attribute "export_path" [abstract] +# return combined_config() +class module_config_1: + custom_setting = 'adhoc setting' + export_path = '/path/to/data' + + +# config defined with @dataclass annotation +# current_impl : works in runtime +# mypy DOES NOT pass +# seems like it doesn't like that non-default attributes (export_path: str) in module config +# are following default attributes (export_path in this config) +# via_dataclass : works both mypy and runtime +# if we comment out export_path, mypy fails (good!) +# src/pkg/via_dataclass.py:56:12:56:28: error: Missing positional argument "export_path" in call to "combined_config" [call-arg] +# return combined_config() +# via_properties: works both mypy and runtime +# if we comment out export_path, mypy fails (good!) +# same error as above + +@dataclass +class module_config_2: + custom_setting: str = 'adhoc setting' + export_path: str = '/path/to/data' + + +# NOTE: ok, if a config attrubute happened to be a classproperty, then it fails mypy +# but it still works in runtime, which is good, easy to migrate if necessary + + +# mixed style config, some attributes are defined via property +# this is quite useful if you want to defer some computations from config import time +# current_impl : works both mypy and runtime +# if we comment out export_path, mypy DOES NOT fail (bad!) +# via_dataclass : FAILS both mypy and runtime +# via_properties: works both mypy and runtime +# if we comment out export_path, mypy fails (good!) +# same error as above +class module_config_3: + custom_setting: str = 'adhoc setting' + + @property + def export_path(self) -> str: + return '/path/to/data' + + +# same mixed style as above, but also a @dataclass annotation +# via_dataclass: FAILS both mypy and runtime +# src/pkg/via_dataclass.py: note: In function "make_config": +# src/pkg/via_dataclass.py:53:5:54:12: error: Definition of "export_path" in base class "module_config" is incompatible with definition in base class "config" [misc] +# class combined_config(user_config, config): +# ^ +# src/pkg/via_dataclass.py:56:12:56:28: error: Missing positional argument "export_path" in call to "combined_config" [call-arg] +# return combined_config() +# ^~~~~~~~~~~~~~~~~ +# via_properties: works both mypy and runtime +# if we comment out export_path, mypy fails (good!) +# same error as above +@dataclass +class module_config_4: + custom_setting: str = 'adhoc setting' + + @classproperty + def export_path(self) -> str: + return '/path/to/data' diff --git a/doc/experiments_with_config/src/pkg/current_impl.py b/doc/experiments_with_config/src/pkg/current_impl.py new file mode 100644 index 0000000..dbb4756 --- /dev/null +++ b/doc/experiments_with_config/src/pkg/current_impl.py @@ -0,0 +1,29 @@ +""" +Currently 'preferred' way of defining configs as of 20240818 +""" +from dataclasses import dataclass + +from pkg.config import module_config as user_config + + +@dataclass +class config(user_config): + export_path: str + + cache_path: str | None = None + + +def run() -> None: + print('hello from', __name__) + + cfg = config + + # check a required attribute + print(f'{cfg.export_path=}') + + # check a non-required attribute with default value + print(f'{cfg.cache_path=}') + + # check a 'dynamically' defined attribute in user config + print(f'{cfg.custom_setting=}') + diff --git a/doc/experiments_with_config/src/pkg/py.typed b/doc/experiments_with_config/src/pkg/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/doc/experiments_with_config/src/pkg/via_dataclass.py b/doc/experiments_with_config/src/pkg/via_dataclass.py new file mode 100644 index 0000000..b2135d8 --- /dev/null +++ b/doc/experiments_with_config/src/pkg/via_dataclass.py @@ -0,0 +1,38 @@ +from dataclasses import dataclass + + +@dataclass +class config: + export_path: str + cache_path: str | None = None + + +def make_config() -> config: + from pkg.config import module_config as user_config + + # NOTE: order is important -- attributes would be added in reverse order + # e.g. first from config, then from user_config -- just what we want + # NOTE: in theory, this works without @dataclass annotation on combined_config + # however, having @dataclass adds extra type checks about missing required attributes + # when we instantiate combined_config + @dataclass + class combined_config(user_config, config): ... + + return combined_config() + + +def run() -> None: + print('hello from', __name__) + + cfg = make_config() + + # check a required attribute + print(f'{cfg.export_path=}') + + # check a non-required attribute with default value + print(f'{cfg.cache_path=}') + + # check a 'dynamically' defined attribute in user config + # NOTE: mypy fails as it has no static knowledge of the attribute + # but kinda expected, not much we can do + print(f'{cfg.custom_setting=}') # type: ignore[attr-defined] diff --git a/doc/experiments_with_config/src/pkg/via_properties.py b/doc/experiments_with_config/src/pkg/via_properties.py new file mode 100644 index 0000000..b40b498 --- /dev/null +++ b/doc/experiments_with_config/src/pkg/via_properties.py @@ -0,0 +1,38 @@ +from abc import abstractmethod + +class config: + @property + @abstractmethod + def export_path(self) -> str: + raise NotImplementedError + + @property + def cache_path(self) -> str | None: + return None + + +def make_config() -> config: + from pkg.config import module_config as user_config + + # NOTE: order is important -- attributes would be added in reverse order + # e.g. first from config, then from user_config -- just what we want + class combined_config(user_config, config): ... + + return combined_config() + + +def run() -> None: + print('hello from', __name__) + + cfg = make_config() + + # check a required attribute + print(f'{cfg.export_path=}') + + # check a non-required attribute with default value + print(f'{cfg.cache_path=}') + + # check a 'dynamically' defined attribute in user config + # NOTE: mypy fails as it has no static knowledge of the attribute + # but kinda expected, not much we can do + print(f'{cfg.custom_setting=}') # type: ignore[attr-defined] diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 3dfed3e..8fc798d 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -3,13 +3,14 @@ Whatsapp data from Android app database (in =/data/data/com.whatsapp/databases/m """ from __future__ import annotations +from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path import sqlite3 from typing import Union, Sequence, Iterator, Optional -from my.core import get_files, Paths, datetime_aware, Res, make_logger, make_config +from my.core import get_files, Paths, datetime_aware, Res, make_logger from my.core.common import unique_everseen from my.core.error import echain, notnone from my.core.sqlite import sqlite_connection @@ -19,17 +20,28 @@ import my.config logger = make_logger(__name__) -@dataclass -class Config(my.config.whatsapp.android): +class Config: # paths[s]/glob to the exported sqlite databases - export_path: Paths - my_user_id: Optional[str] = None + @property + @abstractmethod + def export_path(self) -> Paths: + raise NotImplementedError + + @property + def my_user_id(self) -> Optional[str]: + return None -config = make_config(Config) +def make_config() -> Config: + import my.config as user_config + + class combined_config(user_config.whatsapp.android, Config): ... + + return combined_config() def inputs() -> Sequence[Path]: + config = make_config() return get_files(config.export_path) @@ -62,6 +74,8 @@ Entity = Union[Chat, Sender, Message] def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: # TODO later, split out Chat/Sender objects separately to safe on object creation, similar to other android data sources + config = make_config() + chats = {} for r in db.execute( ''' From 9f017fb29be53866e19ffdf9054b6ac6f011a9cd Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 19 Aug 2024 23:50:12 +0100 Subject: [PATCH 02/55] my.core.pandas: add more tests --- my/core/pandas.py | 126 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 110 insertions(+), 16 deletions(-) diff --git a/my/core/pandas.py b/my/core/pandas.py index 8abbb1f..8ad93cb 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -1,6 +1,7 @@ ''' Various pandas helpers and convenience functions ''' + from __future__ import annotations # todo not sure if belongs to 'core'. It's certainly 'more' core than actual modules, but still not essential @@ -8,12 +9,22 @@ from __future__ import annotations import dataclasses from datetime import datetime, timezone from pprint import pformat -from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Literal, Type, TypeVar +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + Iterator, + Literal, + Type, + TypeVar, +) from decorator import decorator -from . import Res, warnings -from .error import error_to_json, extract_error_datetime +from . import warnings +from .error import Res, error_to_json, extract_error_datetime from .logging import make_logger from .types import Json, asdict @@ -38,7 +49,7 @@ else: S1 = Any -def check_dateish(s: SeriesT[S1]) -> Iterable[str]: +def _check_dateish(s: SeriesT[S1]) -> Iterable[str]: import pandas as pd # noqa: F811 not actually a redefinition ctype = s.dtype @@ -62,9 +73,37 @@ def check_dateish(s: SeriesT[S1]) -> Iterable[str]: def test_check_dateish() -> None: import pandas as pd - # todo just a dummy test to check it doesn't crash, need something meaningful - s1 = pd.Series([1, 2, 3]) - list(check_dateish(s1)) + from .compat import fromisoformat + + # empty series shouldn't warn + assert list(_check_dateish(pd.Series([]))) == [] + + # if no dateimes, shouldn't return any warnings + assert list(_check_dateish(pd.Series([1, 2, 3]))) == [] + + # all values are datetimes, shouldn't warn + # fmt: off + assert list(_check_dateish(pd.Series([ + fromisoformat('2024-08-19T01:02:03'), + fromisoformat('2024-08-19T03:04:05'), + ]))) == [] + # fmt: on + + # mixture of timezones -- should warn + # fmt: off + assert len(list(_check_dateish(pd.Series([ + fromisoformat('2024-08-19T01:02:03'), + fromisoformat('2024-08-19T03:04:05Z'), + ])))) == 1 + # fmt: on + + # TODO hmm. maybe this should actually warn? + # fmt: off + assert len(list(_check_dateish(pd.Series([ + 'whatever', + fromisoformat('2024-08-19T01:02:03'), + ])))) == 0 + # fmt: on # fmt: off @@ -102,7 +141,7 @@ def check_dataframe(f: FuncT, error_col_policy: ErrorColPolicy = 'add_if_missing # makes sense to keep super defensive try: for col, data in df.reset_index().items(): - for w in check_dateish(data): + for w in _check_dateish(data): warnings.low(f"{tag}, column '{col}': {w}") except Exception as e: logger.exception(e) @@ -126,8 +165,7 @@ def error_to_row(e: Exception, *, dt_col: str = 'dt', tz: timezone | None = None return err_dict -# todo not sure about naming -def to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]: +def _to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]: for r in it: if isinstance(r, Exception): yield error_to_row(r) @@ -162,7 +200,7 @@ def as_dataframe(it: Iterable[Res[Any]], schema: Schema | None = None) -> DataFr import pandas as pd # noqa: F811 not actually a redefinition columns = None if schema is None else list(_as_columns(schema).keys()) - return pd.DataFrame(to_jsons(it), columns=columns) + return pd.DataFrame(_to_jsons(it), columns=columns) # ugh. in principle this could be inside the test @@ -172,20 +210,76 @@ def as_dataframe(it: Iterable[Res[Any]], schema: Schema | None = None) -> DataFr # see https://github.com/pytest-dev/pytest/issues/7856 @dataclasses.dataclass class _X: + # FIXME try moving inside? x: int def test_as_dataframe() -> None: + import numpy as np + import pandas as pd import pytest + from pandas.testing import assert_frame_equal - it = (dict(i=i, s=f'str{i}') for i in range(10)) + from .compat import fromisoformat + + it = (dict(i=i, s=f'str{i}') for i in range(5)) with pytest.warns(UserWarning, match=r"No 'error' column") as record_warnings: # noqa: F841 df: DataFrameT = as_dataframe(it) # todo test other error col policies - assert list(df.columns) == ['i', 's', 'error'] - assert len(as_dataframe([])) == 0 + # fmt: off + assert_frame_equal( + df, + pd.DataFrame({ + 'i' : [0 , 1 , 2 , 3 , 4 ], + 's' : ['str0', 'str1', 'str2', 'str3', 'str4'], + # NOTE: error column is always added + 'error': [None , None , None , None , None ], + }), + ) + # fmt: on + assert_frame_equal(as_dataframe([]), pd.DataFrame(columns=['error'])) - # makes sense to specify the schema so the downstream program doesn't fail in case of empty iterable df2: DataFrameT = as_dataframe([], schema=_X) - assert list(df2.columns) == ['x', 'error'] + assert_frame_equal( + df2, + # FIXME hmm. x column type should be an int?? and error should be string (or object??) + pd.DataFrame(columns=['x', 'error']), + ) + + @dataclasses.dataclass + class S: + value: str + + def it2() -> Iterator[Res[S]]: + yield S(value='test') + yield RuntimeError('i failed') + + df = as_dataframe(it2()) + # fmt: off + assert_frame_equal( + df, + pd.DataFrame(data={ + 'value': ['test', np.nan ], + 'error': [np.nan, 'RuntimeError: i failed\n'], + 'dt' : [np.nan, np.nan ], + }).astype(dtype={'dt': 'float'}), # FIXME should be datetime64 as below + ) + # fmt: on + + def it3() -> Iterator[Res[S]]: + yield S(value='aba') + yield RuntimeError('whoops') + yield S(value='cde') + yield RuntimeError('exception with datetime', fromisoformat('2024-08-19T22:47:01Z')) + + df = as_dataframe(it3()) + + # fmt: off + assert_frame_equal(df, pd.DataFrame(data={ + 'value': ['aba' , np.nan , 'cde' , np.nan ], + 'error': [np.nan, 'RuntimeError: whoops\n', np.nan, "RuntimeError: ('exception with datetime', datetime.datetime(2024, 8, 19, 22, 47, 1, tzinfo=datetime.timezone.utc))\n"], + # note: dt column is added even if errors don't have an associated datetime + 'dt' : [np.nan, np.nan , np.nan, '2024-08-19 22:47:01+00:00'], + }).astype(dtype={'dt': 'datetime64[ns, UTC]'})) + # fmt: on From 0e0ab5fe24da73464f188b1fee14baceac04691c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Thu, 22 Aug 2024 01:44:32 +0100 Subject: [PATCH 03/55] try using Protocol for my.whatsapp.android --- my/whatsapp/android.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 8fc798d..58ac612 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -3,12 +3,11 @@ Whatsapp data from Android app database (in =/data/data/com.whatsapp/databases/m """ from __future__ import annotations -from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path import sqlite3 -from typing import Union, Sequence, Iterator, Optional +from typing import Union, Sequence, Iterator, Optional, Protocol from my.core import get_files, Paths, datetime_aware, Res, make_logger from my.core.common import unique_everseen @@ -20,16 +19,11 @@ import my.config logger = make_logger(__name__) -class Config: +class Config(Protocol): # paths[s]/glob to the exported sqlite databases - @property - @abstractmethod - def export_path(self) -> Paths: - raise NotImplementedError + export_path: Paths - @property - def my_user_id(self) -> Optional[str]: - return None + my_user_id: Optional[str] = None def make_config() -> Config: From d154825591b2b2c074b42852cea9ddd510928fca Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 23 Aug 2024 00:00:16 +0100 Subject: [PATCH 04/55] my.bluemaestro: make config construction lazy following the discussions here: https://github.com/karlicoss/HPI/issues/46#issuecomment-2295464073 --- my/bluemaestro.py | 51 +++++++++++++++++++++++++++++++------------- tests/bluemaestro.py | 8 ++----- 2 files changed, 38 insertions(+), 21 deletions(-) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 3e25cae..12c114f 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -4,36 +4,58 @@ """ # todo most of it belongs to DAL... but considering so few people use it I didn't bother for now +import re +import sqlite3 +from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path -import re -import sqlite3 -from typing import Iterable, Sequence, Set, Optional +from typing import Iterable, Optional, Protocol, Sequence, Set import pytz from my.core import ( + Paths, + Res, + Stats, get_files, make_logger, - Res, stat, - Stats, - influxdb, + unwrap, ) from my.core.cachew import mcachew -from my.core.error import unwrap from my.core.pandas import DataFrameT, as_dataframe from my.core.sqlite import sqlite_connect_immutable -from my.config import bluemaestro as config + +class config(Protocol): + @property + @abstractmethod + def export_path(self) -> Paths: + raise NotImplementedError + + @property + def tz(self) -> pytz.BaseTzInfo: + # fixme: later, rely on the timezone provider + # NOTE: the timezone should be set with respect to the export date!!! + return pytz.timezone('Europe/London') + # TODO when I change tz, check the diff + + +def make_config() -> config: + from my.config import bluemaestro as user_config + + class combined_config(user_config, config): ... + + return combined_config() logger = make_logger(__name__) def inputs() -> Sequence[Path]: - return get_files(config.export_path) + cfg = make_config() + return get_files(cfg.export_path) Celsius = float @@ -50,12 +72,6 @@ class Measurement: dewpoint: Celsius -# fixme: later, rely on the timezone provider -# NOTE: the timezone should be set with respect to the export date!!! -tz = pytz.timezone('Europe/London') -# TODO when I change tz, check the diff - - def is_bad_table(name: str) -> bool: # todo hmm would be nice to have a hook that can patch any module up to delegate = getattr(config, 'is_bad_table', None) @@ -64,6 +80,9 @@ def is_bad_table(name: str) -> bool: @mcachew(depends_on=inputs) def measurements() -> Iterable[Res[Measurement]]: + cfg = make_config() + tz = cfg.tz + # todo ideally this would be via arguments... but needs to be lazy paths = inputs() total = len(paths) @@ -211,6 +230,8 @@ def dataframe() -> DataFrameT: def fill_influxdb() -> None: + from my.core import influxdb + influxdb.fill(measurements(), measurement=__name__) diff --git a/tests/bluemaestro.py b/tests/bluemaestro.py index 84d3eb0..63ce589 100644 --- a/tests/bluemaestro.py +++ b/tests/bluemaestro.py @@ -1,19 +1,15 @@ from pathlib import Path -from typing import TYPE_CHECKING, Iterator, Any +from typing import Iterator from more_itertools import one import pytest -if TYPE_CHECKING: - from my.bluemaestro import Measurement -else: - Measurement = Any +from my.bluemaestro import measurements, Measurement def ok_measurements() -> Iterator[Measurement]: - from my.bluemaestro import measurements for m in measurements(): assert not isinstance(m, Exception) yield m From 5a67f0bafe354514b3490385430a73ad0f55b970 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 23 Aug 2024 00:47:00 +0100 Subject: [PATCH 05/55] pdfs: migrate config to Protocol with properties allowes to remove a whole bunch of hacky crap from tests! --- my/pdfs.py | 86 +++++++++++++++++++++++----------------------- my/tests/common.py | 4 +++ tests/pdfs.py | 30 +++++----------- 3 files changed, 56 insertions(+), 64 deletions(-) diff --git a/my/pdfs.py b/my/pdfs.py index 0ab4af3..524c68b 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -1,64 +1,64 @@ ''' PDF documents and annotations on your filesystem ''' + REQUIRES = [ 'git+https://github.com/0xabu/pdfannots', # todo not sure if should use pypi version? ] -from datetime import datetime -from dataclasses import dataclass -import io -from pathlib import Path import time -from typing import NamedTuple, List, Optional, Iterator, Sequence +from datetime import datetime +from pathlib import Path +from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence +import pdfannots +from more_itertools import bucket -from my.core import LazyLogger, get_files, Paths, PathIsh +from my.core import PathIsh, Paths, Stats, get_files, make_logger, stat from my.core.cachew import mcachew -from my.core.cfg import Attrs, make_config from my.core.error import Res, split_errors -from more_itertools import bucket -import pdfannots - - -from my.config import pdfs as user_config - -@dataclass -class pdfs(user_config): - paths: Paths = () # allowed to be empty for 'filelist' logic +class config(Protocol): + @property + def paths(self) -> Paths: + return () # allowed to be empty for 'filelist' logic def is_ignored(self, p: Path) -> bool: """ - Used to ignore some extremely heavy files - is_ignored function taken either from config, - or if not defined, it's a function that returns False + You can override this in user config if you want to ignore some files that are tooheavy """ - user_ignore = getattr(user_config, 'is_ignored', None) - if user_ignore is not None: - return user_ignore(p) - return False - @staticmethod - def _migration(attrs: Attrs) -> Attrs: - roots = 'roots' - if roots in attrs: # legacy name - attrs['paths'] = attrs[roots] - from my.core.warnings import high - high(f'"{roots}" is deprecated! Use "paths" instead.') - return attrs + +def make_config() -> config: + from my.config import pdfs as user_config + + class migration: + @property + def paths(self) -> Paths: + roots = getattr(user_config, 'roots', None) + if roots is not None: + from my.core.warnings import high + + high('"roots" is deprecated! Use "paths" instead.') + return roots + else: + return () + + class combined_config(user_config, migration, config): ... + + return combined_config() -config = make_config(pdfs, migration=pdfs._migration) +logger = make_logger(__name__) -logger = LazyLogger(__name__) def inputs() -> Sequence[Path]: - all_files = get_files(config.paths, glob='**/*.pdf') - return [p for p in all_files if not config.is_ignored(p)] + cfg = make_config() + all_files = get_files(cfg.paths, glob='**/*.pdf') + return [p for p in all_files if not cfg.is_ignored(p)] # TODO canonical names/fingerprinting? @@ -121,14 +121,13 @@ def _iter_annotations(pdfs: Sequence[Path]) -> Iterator[Res[Annotation]]: # todo how to print to stdout synchronously? # todo global config option not to use pools? useful for debugging.. from concurrent.futures import ProcessPoolExecutor + from my.core.utils.concurrent import DummyExecutor + workers = None # use 0 for debugging Pool = DummyExecutor if workers == 0 else ProcessPoolExecutor with Pool(workers) as pool: - futures = [ - pool.submit(get_annots, pdf) - for pdf in pdfs - ] + futures = [pool.submit(get_annots, pdf) for pdf in pdfs] for f, pdf in zip(futures, pdfs): try: yield from f.result() @@ -161,11 +160,13 @@ class Pdf(NamedTuple): return self.created -def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]]=None) -> Iterator[Res[Pdf]]: +def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]] = None) -> Iterator[Res[Pdf]]: if filelist is not None: # hacky... keeping it backwards compatible # https://github.com/karlicoss/HPI/pull/74 - config.paths = filelist + from my.config import pdfs as user_config + + user_config.paths = filelist ait = annotations() vit, eit = split_errors(ait, ET=Exception) @@ -176,10 +177,9 @@ def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]]=None) -> Iterator[Re yield from eit -from my.core import stat, Stats def stats() -> Stats: return { - **stat(annotations) , + **stat(annotations), **stat(annotated_pdfs), } diff --git a/my/tests/common.py b/my/tests/common.py index e3060e1..f8b645d 100644 --- a/my/tests/common.py +++ b/my/tests/common.py @@ -20,6 +20,10 @@ def reset_modules() -> None: ''' to_unload = [m for m in sys.modules if re.match(r'my[.]?', m)] for m in to_unload: + if 'my.pdfs' in m: + # temporary hack -- since my.pdfs migrated to a 'lazy' config, this isn't necessary anymore + # but if we reset module anyway, it confuses the ProcessPool inside my.pdfs + continue del sys.modules[m] diff --git a/tests/pdfs.py b/tests/pdfs.py index 63b1319..6db669f 100644 --- a/tests/pdfs.py +++ b/tests/pdfs.py @@ -1,17 +1,16 @@ +import inspect from pathlib import Path +import pytest from more_itertools import ilen -import pytest - +from my.core.cfg import tmp_config from my.tests.common import testdata +from my.pdfs import annotated_pdfs, annotations, get_annots + def test_module(with_config) -> None: - # TODO crap. if module is imported too early (on the top level, it makes it super hard to override config) - # need to at least detect it... - from my.pdfs import annotations, annotated_pdfs - # todo check types etc as well assert ilen(annotations()) >= 3 assert ilen(annotated_pdfs()) >= 1 @@ -22,12 +21,13 @@ def test_with_error(with_config, tmp_path: Path) -> None: root = tmp_path g = root / 'garbage.pdf' g.write_text('garbage') + from my.config import pdfs + # meh. otherwise legacy config value 'wins' del pdfs.roots # type: ignore[attr-defined] pdfs.paths = (root,) - from my.pdfs import annotations annots = list(annotations()) [annot] = annots assert isinstance(annot, Exception) @@ -35,9 +35,6 @@ def test_with_error(with_config, tmp_path: Path) -> None: @pytest.fixture def with_config(): - from my.tests.common import reset_modules - reset_modules() # todo ugh.. getting boilerplaty.. need to make it a bit more automatic.. - # extra_data = Path(__file__).absolute().parent / 'extra/data/polar' # assert extra_data.exists(), extra_data # todo hmm, turned out no annotations in these ones.. whatever @@ -47,13 +44,9 @@ def with_config(): testdata(), ] - import my.core.cfg as C - with C.tmp_config() as config: + with tmp_config() as config: config.pdfs = user_config - try: - yield - finally: - reset_modules() + yield EXPECTED_HIGHLIGHTS = { @@ -68,8 +61,6 @@ def test_get_annots() -> None: Test get_annots, with a real PDF file get_annots should return a list of three Annotation objects """ - from my.pdfs import get_annots - annotations = get_annots(testdata() / 'pdfs' / 'Information Architecture for the World Wide Web.pdf') assert len(annotations) == 3 assert set([a.highlight for a in annotations]) == EXPECTED_HIGHLIGHTS @@ -80,12 +71,9 @@ def test_annotated_pdfs_with_filelist() -> None: Test annotated_pdfs, with a real PDF file annotated_pdfs should return a list of one Pdf object, with three Annotations """ - from my.pdfs import annotated_pdfs - filelist = [testdata() / 'pdfs' / 'Information Architecture for the World Wide Web.pdf'] annotations_generator = annotated_pdfs(filelist=filelist) - import inspect assert inspect.isgeneratorfunction(annotated_pdfs) highlights_from_pdfs = [] From 1215181af533ba49bbb7658de66b259333e90310 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 16:36:34 +0100 Subject: [PATCH 06/55] core: move stuff from tests/demo.py to my/core/tests/test_config.py also clean all this up a bit --- my/core/__init__.py | 4 +- my/core/tests/test_config.py | 132 +++++++++++++++++++++++++++++++++++ my/demo.py | 53 ++++++++------ tests/demo.py | 118 ------------------------------- 4 files changed, 164 insertions(+), 143 deletions(-) create mode 100644 my/core/tests/test_config.py delete mode 100644 tests/demo.py diff --git a/my/core/__init__.py b/my/core/__init__.py index 19be7fe..ba633f6 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING from .cfg import make_config from .common import PathIsh, Paths, get_files from .compat import assert_never -from .error import Res, unwrap +from .error import Res, unwrap, notnone from .logging import ( make_logger, ) @@ -42,7 +42,7 @@ __all__ = [ '__NOT_HPI_MODULE__', - 'Res', 'unwrap', + 'Res', 'unwrap', 'notnone', 'dataclass', 'Path', ] diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py new file mode 100644 index 0000000..c76f5d9 --- /dev/null +++ b/my/core/tests/test_config.py @@ -0,0 +1,132 @@ +""" +Various tests that are checking behaviour of user config wrt to various things +""" + +import sys +from pathlib import Path + +import pytest +import pytz +from more_itertools import ilen + +import my.config +from my.core import notnone +from my.demo import items, make_config + + +# run the same test multiple times to make sure there are not issues with import order etc +@pytest.mark.parametrize('run_id', ['1', '2']) +def test_override_config(tmp_path: Path, run_id: str) -> None: + class user_config: + username = f'user_{run_id}' + data_path = f'{tmp_path}/*.json' + + my.config.demo = user_config # type: ignore[misc, assignment] + + [item1, item2] = items() + assert item1.username == f'user_{run_id}' + assert item2.username == f'user_{run_id}' + + +@pytest.mark.skip(reason="won't work at the moment because of inheritance") +def test_dynamic_config_simplenamespace(tmp_path: Path) -> None: + from types import SimpleNamespace + + user_config = SimpleNamespace( + username='user3', + data_path=f'{tmp_path}/*.json', + ) + my.config.demo = user_config # type: ignore[misc, assignment] + + cfg = make_config() + + assert cfg.username == 'user3' + + +def test_mixin_attribute_handling(tmp_path: Path) -> None: + """ + Tests that arbitrary mixin attributes work with our config handling pattern + """ + + nytz = pytz.timezone('America/New_York') + + class user_config: + # check that override is taken into the account + timezone = nytz + + irrelevant = 'hello' + + username = 'UUU' + data_path = f'{tmp_path}/*.json' + + my.config.demo = user_config # type: ignore[misc, assignment] + + cfg = make_config() + + assert cfg.username == 'UUU' + + # mypy doesn't know about it, but the attribute is there + assert getattr(cfg, 'irrelevant') == 'hello' + + # check that overridden default attribute is actually getting overridden + assert cfg.timezone == nytz + + [item1, item2] = items() + assert item1.username == 'UUU' + assert notnone(item1.dt.tzinfo).zone == nytz.zone # type: ignore[attr-defined] + assert item2.username == 'UUU' + assert notnone(item2.dt.tzinfo).zone == nytz.zone # type: ignore[attr-defined] + + +# use multiple identical tests to make sure there are no issues with cached imports etc +@pytest.mark.parametrize('run_id', ['1', '2']) +def test_dynamic_module_import(tmp_path: Path, run_id: str) -> None: + """ + Test for dynamic hackery in config properties + e.g. importing some external modules + """ + + ext = tmp_path / 'external' + ext.mkdir() + (ext / '__init__.py').write_text( + ''' +def transform(x): + from .submodule import do_transform + return do_transform(x) + +''' + ) + (ext / 'submodule.py').write_text( + f''' +def do_transform(x): + return {{"total_{run_id}": sum(x.values())}} +''' + ) + + class user_config: + username = 'someuser' + data_path = f'{tmp_path}/*.json' + external = f'{ext}' + + my.config.demo = user_config # type: ignore[misc, assignment] + + [item1, item2] = items() + assert item1.raw == {f'total_{run_id}': 1 + 123}, item1 + assert item2.raw == {f'total_{run_id}': 2 + 456}, item2 + + # need to reset these modules, otherwise they get cached + # kind of relevant to my.core.cfg.tmp_config + sys.modules.pop('external', None) + sys.modules.pop('external.submodule', None) + + +@pytest.fixture(autouse=True) +def prepare_data(tmp_path: Path): + (tmp_path / 'data.json').write_text( + ''' +[ + {"key": 1, "value": 123}, + {"key": 2, "value": 456} +] +''' + ) diff --git a/my/demo.py b/my/demo.py index 645be4f..e27b5dd 100644 --- a/my/demo.py +++ b/my/demo.py @@ -2,19 +2,23 @@ Just a demo module for testing and documentation purposes ''' -from .core import Paths, PathIsh - -from typing import Optional -from datetime import tzinfo, timezone - -from my.config import demo as user_config +import json +from abc import abstractmethod from dataclasses import dataclass +from datetime import datetime, timezone, tzinfo +from pathlib import Path +from typing import Iterable, Optional, Protocol, Sequence + +from my.core import Json, PathIsh, Paths, get_files -@dataclass -class demo(user_config): +class config(Protocol): data_path: Paths + + # this is to check required attribute handling username: str + + # this is to check optional attribute handling timezone: tzinfo = timezone.utc external: Optional[PathIsh] = None @@ -23,47 +27,50 @@ class demo(user_config): def external_module(self): rpath = self.external if rpath is not None: - from .core.utils.imports import import_dir + from my.core.utils.imports import import_dir + return import_dir(rpath) - import my.config.repos.external as m # type: ignore + import my.config.repos.external as m # type: ignore + return m -from .core import make_config -config = make_config(demo) +def make_config() -> config: + from my.config import demo as user_config -# TODO not sure about type checking? -external = config.external_module + class combined_config(user_config, config): ... + return combined_config() -from pathlib import Path -from typing import Sequence, Iterable -from datetime import datetime -from .core import Json, get_files @dataclass class Item: ''' Some completely arbitrary artificial stuff, just for testing ''' + username: str raw: Json dt: datetime def inputs() -> Sequence[Path]: - return get_files(config.data_path) + cfg = make_config() + return get_files(cfg.data_path) -import json def items() -> Iterable[Item]: + cfg = make_config() + + transform = (lambda i: i) if cfg.external is None else cfg.external_module.transform + for f in inputs(): - dt = datetime.fromtimestamp(f.stat().st_mtime, tz=config.timezone) + dt = datetime.fromtimestamp(f.stat().st_mtime, tz=cfg.timezone) j = json.loads(f.read_text()) for raw in j: yield Item( - username=config.username, - raw=external.identity(raw), + username=cfg.username, + raw=transform(raw), dt=dt, ) diff --git a/tests/demo.py b/tests/demo.py deleted file mode 100644 index 73a6c65..0000000 --- a/tests/demo.py +++ /dev/null @@ -1,118 +0,0 @@ -import sys -from pathlib import Path -from more_itertools import ilen - -# TODO NOTE: this wouldn't work because of an early my.config.demo import -# from my.demo import items - -def test_dynamic_config_1(tmp_path: Path) -> None: - import my.config - - class user_config: - username = 'user' - data_path = f'{tmp_path}/*.json' - external = f'{tmp_path}/external' - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import items - [item1, item2] = items() - assert item1.username == 'user' - - -# exactly the same test, but using a different config, to test out the behaviour w.r.t. import order -def test_dynamic_config_2(tmp_path: Path) -> None: - # doesn't work without it! - # because the config from test_dybamic_config_1 is cached in my.demo.demo - del sys.modules['my.demo'] - - import my.config - - class user_config: - username = 'user2' - data_path = f'{tmp_path}/*.json' - external = f'{tmp_path}/external' - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import items - [item1, item2] = items() - assert item1.username == 'user2' - - -import pytest - -@pytest.mark.skip(reason="won't work at the moment because of inheritance") -def test_dynamic_config_simplenamespace(tmp_path: Path) -> None: - # doesn't work without it! - # because the config from test_dybamic_config_1 is cached in my.demo.demo - del sys.modules['my.demo'] - - import my.config - from types import SimpleNamespace - - user_config = SimpleNamespace( - username='user3', - data_path=f'{tmp_path}/*.json', - ) - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import config - assert config.username == 'user3' - - -# make sure our config handling pattern does it as expected -def test_attribute_handling(tmp_path: Path) -> None: - # doesn't work without it! - # because the config from test_dybamic_config_1 is cached in my.demo.demo - del sys.modules['my.demo'] - - import pytz - nytz = pytz.timezone('America/New_York') - - import my.config - class user_config: - # check that override is taken into the account - timezone = nytz - - irrelevant = 'hello' - - username = 'UUU' - data_path = f'{tmp_path}/*.json' - external = f'{tmp_path}/external' - - - my.config.demo = user_config # type: ignore[misc, assignment] - - from my.demo import config - - assert config.username == 'UUU' - - # mypy doesn't know about it, but the attribute is there - assert getattr(config, 'irrelevant') == 'hello' - - # check that overridden default attribute is actually getting overridden - assert config.timezone == nytz - - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - (tmp_path / 'data.json').write_text(''' -[ - {"key1": 1}, - {"key2": 2} -] -''') - ext = tmp_path / 'external' - ext.mkdir() - (ext / '__init__.py').write_text(''' -def identity(x): - from .submodule import hello - hello(x) - return x - -''') - (ext / 'submodule.py').write_text('hello = lambda x: print("hello " + str(x))') - yield - ex = 'my.config.repos.external' - if ex in sys.modules: - del sys.modules[ex] From 2ff2dcfc003d2ff0e0440d91b2778eee3c2e851c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 18:51:34 +0100 Subject: [PATCH 07/55] tests: move test checkign for my_config handling to core/tests/test_config.py allows to remove the hacky reset_modules thing from setup fixture --- my/core/tests/test_config.py | 47 ++++++++++++++++++++++++++++++++++++ tests/config.py | 41 ++----------------------------- 2 files changed, 49 insertions(+), 39 deletions(-) diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py index c76f5d9..a318a95 100644 --- a/my/core/tests/test_config.py +++ b/my/core/tests/test_config.py @@ -3,6 +3,7 @@ Various tests that are checking behaviour of user config wrt to various things """ import sys +import os from pathlib import Path import pytest @@ -13,6 +14,10 @@ import my.config from my.core import notnone from my.demo import items, make_config +from .common import tmp_environ_set + +# TODO would be nice to randomize test order here to catch various config issues + # run the same test multiple times to make sure there are not issues with import order etc @pytest.mark.parametrize('run_id', ['1', '2']) @@ -120,6 +125,48 @@ def do_transform(x): sys.modules.pop('external.submodule', None) +@pytest.mark.parametrize('run_id', ['1', '2']) +def test_my_config_env_variable(tmp_path: Path, run_id: str) -> None: + """ + Tests handling of MY_CONFIG variable + """ + + # ugh. so by this point, my.config is already loaded (default stub), so we need to unload it + sys.modules.pop('my.config', None) + # but my.config itself relies on my.core.init hook, so unless it's reloaded too it wouldn't help + sys.modules.pop('my.core', None) + sys.modules.pop('my.core.init', None) + # it's a bit of a mouthful of course, but in most cases MY_CONFIG would be set once + # , and before hpi runs, so hopefully it's not a huge deal + cfg_dir = tmp_path / 'my' + cfg_file = cfg_dir / 'config.py' + cfg_dir.mkdir() + + cfg_file.write_text( + f''' +# print("IMPORTING CONFIG {run_id}") +class demo: + username = 'xxx_{run_id}' + data_path = r'{tmp_path}{os.sep}*.json' # need raw string for windows... +''' + ) + + with tmp_environ_set('MY_CONFIG', str(tmp_path)): + [item1, item2] = items() + assert item1.username == f'xxx_{run_id}' + assert item2.username == f'xxx_{run_id}' + + # sigh.. so this is cached in sys.path + # so it takes precedence later during next import, not giving the MY_CONFIG hook + # (imported from builtin my.config) to kick in + sys.path.remove(str(tmp_path)) + + # FIXME ideally this shouldn't be necessary? + # remove this after we fixup my.tests.reddit and my.tests.commits + # (they were failing ci when running all tests) + sys.modules.pop('my.config', None) + + @pytest.fixture(autouse=True) def prepare_data(tmp_path: Path): (tmp_path / 'data.json').write_text( diff --git a/tests/config.py b/tests/config.py index 101f7df..acfe1f1 100644 --- a/tests/config.py +++ b/tests/config.py @@ -1,6 +1,7 @@ from pathlib import Path +# TODO move this somewhere else -- there are more specific tests covering this now def test_dynamic_configuration(notes: Path) -> None: import pytz from types import SimpleNamespace as NS @@ -26,42 +27,11 @@ def test_dynamic_configuration(notes: Path) -> None: import pytest -def test_environment_variable(tmp_path: Path) -> None: - cfg_dir = tmp_path / 'my' - cfg_file = cfg_dir / 'config.py' - cfg_dir.mkdir() - cfg_file.write_text(''' -class feedly: - pass -class just_for_test: - pass -''') - - import os - oenv = dict(os.environ) - try: - os.environ['MY_CONFIG'] = str(tmp_path) - # should not raise at least - import my.rss.feedly - - import my.config as c - assert hasattr(c, 'just_for_test') - finally: - os.environ.clear() - os.environ.update(oenv) - - import sys - # TODO wtf??? doesn't work without unlink... is it caching something? - cfg_file.unlink() - del sys.modules['my.config'] # meh.. - - import my.config as c - assert not hasattr(c, 'just_for_test') - from dataclasses import dataclass +# TODO this test should probs be deprecated? it's more of a documentation? def test_user_config() -> None: from my.core.common import classproperty class user_config: @@ -117,10 +87,3 @@ Some misc stuff yield ndir finally: pass - - -@pytest.fixture(autouse=True) -def prepare(): - from my.tests.common import reset_modules - reset_modules() - yield From 7cae9d5bf367f0c5d2a1cc158cb5782a523666b1 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 22:36:54 +0100 Subject: [PATCH 08/55] my.google.takeout.paths: migrate to new style lazy config also clean up tests a little and move into my.tests.location.google --- my/google/takeout/paths.py | 45 ++++++++++++++++++------------ my/tests/common.py | 4 +++ my/tests/location/google.py | 55 +++++++++++++++++++++++++++++++++++++ tests/location.py | 28 ------------------- 4 files changed, 86 insertions(+), 46 deletions(-) create mode 100644 my/tests/location/google.py delete mode 100644 tests/location.py diff --git a/my/google/takeout/paths.py b/my/google/takeout/paths.py index 5b53149..948cf2e 100644 --- a/my/google/takeout/paths.py +++ b/my/google/takeout/paths.py @@ -2,44 +2,53 @@ Module for locating and accessing [[https://takeout.google.com][Google Takeout]] data ''' -from dataclasses import dataclass -from ...core.common import Paths, get_files -from ...core.util import __NOT_HPI_MODULE__ - -from my.config import google as user_config +from abc import abstractmethod +from pathlib import Path +from typing import Iterable, Optional, Protocol from more_itertools import last -@dataclass -class google(user_config): - takeout_path: Paths # path/paths/glob for the takeout zips -### +from my.core import __NOT_HPI_MODULE__, Paths, get_files + + +class config: + """ + path/paths/glob for the takeout zips + """ + + @property + @abstractmethod + def takeout_path(self) -> Paths: + raise NotImplementedError + # TODO rename 'google' to 'takeout'? not sure -from ...core.cfg import make_config -config = make_config(google) -from pathlib import Path -from typing import Optional, Iterable +def make_config() -> config: + from my.config import google as user_config + + class combined_config(user_config, config): ... + + return combined_config() -def get_takeouts(*, path: Optional[str]=None) -> Iterable[Path]: +def get_takeouts(*, path: Optional[str] = None) -> Iterable[Path]: """ Sometimes google splits takeout into multiple archives, so we need to detect the ones that contain the path we need """ - # TODO FIXME zip is not great.. + # TODO zip is not great.. # allow a lambda expression? that way the user could restrict it - for takeout in get_files(config.takeout_path, glob='*.zip'): + cfg = make_config() + for takeout in get_files(cfg.takeout_path, glob='*.zip'): if path is None or (takeout / path).exists(): yield takeout -def get_last_takeout(*, path: Optional[str]=None) -> Optional[Path]: +def get_last_takeout(*, path: Optional[str] = None) -> Optional[Path]: return last(get_takeouts(path=path), default=None) # TODO might be a good idea to merge across multiple takeouts... # perhaps even a special takeout module that deals with all of this automatically? # e.g. accumulate, filter and maybe report useless takeouts? - diff --git a/my/tests/common.py b/my/tests/common.py index f8b645d..962ee46 100644 --- a/my/tests/common.py +++ b/my/tests/common.py @@ -31,3 +31,7 @@ def testdata() -> Path: d = Path(__file__).absolute().parent.parent.parent / 'testdata' assert d.exists(), d return d + + +# prevent pytest from treating this as test +testdata.__test__ = False # type: ignore[attr-defined] diff --git a/my/tests/location/google.py b/my/tests/location/google.py new file mode 100644 index 0000000..612522b --- /dev/null +++ b/my/tests/location/google.py @@ -0,0 +1,55 @@ +""" +Tests for LEGACY location provider + +Keeping for now for backwards compatibility +""" + +from pathlib import Path + +import pytest +from more_itertools import one + +from my.core.cfg import tmp_config +from my.location.google import locations + + +def test_google_locations() -> None: + locs = list(locations()) + assert len(locs) == 3810, len(locs) + + last = locs[-1] + assert last.dt.strftime('%Y%m%d %H:%M:%S') == '20170802 13:01:56' # should be utc + # todo approx + assert last.lat == 46.5515350 + assert last.lon == 16.4742742 + # todo check altitude + + +@pytest.fixture(autouse=True) +def prepare(tmp_path: Path): + + # TODO could just pick a part of shared config? not sure + _takeout_path = _prepare_takeouts_dir(tmp_path) + + class google: + takeout_path = _takeout_path + + with tmp_config() as config: + config.google = google + yield + + +def _prepare_takeouts_dir(tmp_path: Path) -> Path: + from ..common import testdata + + try: + track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) + except ValueError: + raise RuntimeError('testdata not found, setup git submodules?') + + # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs + import zipfile + + with zipfile.ZipFile(tmp_path / 'takeout.zip', 'w') as zf: + zf.writestr('Takeout/Location History/Location History.json', track.read_bytes()) + return tmp_path diff --git a/tests/location.py b/tests/location.py deleted file mode 100644 index 2597d5e..0000000 --- a/tests/location.py +++ /dev/null @@ -1,28 +0,0 @@ -from pathlib import Path - -import pytest - - -def test() -> None: - from my.location.google import locations - locs = list(locations()) - assert len(locs) == 3810 - - last = locs[-1] - assert last.dt.strftime('%Y%m%d %H:%M:%S') == '20170802 13:01:56' # should be utc - # todo approx - assert last.lat == 46.5515350 - assert last.lon == 16.4742742 - # todo check altitude - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - from .shared_config import temp_config - user_config = temp_config(tmp_path) - - import my.core.cfg as C - with C.tmp_config() as config: - config.google = user_config.google - yield - From 094519acafc681d15a0e395e1dbe9b62641846ce Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 25 Aug 2024 23:06:26 +0100 Subject: [PATCH 09/55] tests: disable cachew in my.tests subpackage --- my/tests/conftest.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 my/tests/conftest.py diff --git a/my/tests/conftest.py b/my/tests/conftest.py new file mode 100644 index 0000000..4e67f71 --- /dev/null +++ b/my/tests/conftest.py @@ -0,0 +1,8 @@ +import pytest + +# I guess makes sense by default +@pytest.fixture(autouse=True) +def without_cachew(): + from my.core.cachew import disabled_cachew + with disabled_cachew(): + yield From 270080bd562aec0489a9b3573e00882756736342 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 00:08:09 +0100 Subject: [PATCH 10/55] core.error: better defensive handling for my.core.source when parts of config are missing --- my/core/error.py | 27 +++++++++++++++++++++++---- my/core/source.py | 2 +- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/my/core/error.py b/my/core/error.py index c4dff07..7489f69 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -201,7 +201,12 @@ def error_to_json(e: Exception) -> Json: MODULE_SETUP_URL = 'https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#private-configuration-myconfig' -def warn_my_config_import_error(err: Union[ImportError, AttributeError], help_url: Optional[str] = None) -> bool: +def warn_my_config_import_error( + err: Union[ImportError, AttributeError], + *, + help_url: Optional[str] = None, + module_name: Optional[str] = None, +) -> bool: """ If the user tried to import something from my.config but it failed, possibly due to missing the config block in my.config? @@ -233,10 +238,24 @@ See {help_url}\ config_obj = cast(object, getattr(err, 'obj')) # the object that caused the attribute error # e.g. active_browser for my.browser nested_block_name = err.name - if config_obj.__module__ == 'my.config': - click.secho(f"""You're likely missing the nested config block for '{getattr(config_obj, '__name__', str(config_obj))}.{nested_block_name}'. + errmsg = f"""You're likely missing the nested config block for '{getattr(config_obj, '__name__', str(config_obj))}.{nested_block_name}'. See {help_url} or check the corresponding module.py file for an example\ -""", fg='yellow', err=True) +""" + if config_obj.__module__ == 'my.config': + click.secho(errmsg, fg='yellow', err=True) + return True + if module_name is not None and nested_block_name == module_name.split('.')[-1]: + # this tries to cover cases like these + # user config: + # class location: + # class via_ip: + # accuracy = 10_000 + # then when we import it, we do something like + # from my.config import location + # user_config = location.via_ip + # so if location is present, but via_ip is not, we get + # AttributeError: type object 'location' has no attribute 'via_ip' + click.secho(errmsg, fg='yellow', err=True) return True else: click.echo(f"Unexpected error... {err}", err=True) diff --git a/my/core/source.py b/my/core/source.py index 9488ae2..6e0a78a 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -65,7 +65,7 @@ class core: """) # try to check if this is a config error or based on dependencies not being installed if isinstance(err, (ImportError, AttributeError)): - matched_config_err = warn_my_config_import_error(err, help_url=help_url) + matched_config_err = warn_my_config_import_error(err, module_name=module_name, help_url=help_url) # if we determined this wasn't a config error, and it was an attribute error # it could be *any* attribute error -- we should raise this since its otherwise a fatal error # from some code in the module failing From a5643206a0dc2735bc383ef700afd71439d8b192 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 02:00:51 +0100 Subject: [PATCH 11/55] general: make time.tz.via_location user config lazy, move tests to my.tests package also gets rid of the problematic reset_modules thingie --- my/calendar/holidays.py | 2 +- my/core/compat.py | 2 + my/location/fallback/via_ip.py | 4 +- my/tests/calendar.py | 9 ++ my/tests/common.py | 16 --- my/tests/conftest.py | 2 + .../tests/location/fallback.py | 54 +++++---- .../tests/shared_tz_config.py | 75 ++++++------ my/tests/tz.py | 107 ++++++++++++++++++ my/time/tz/via_location.py | 107 ++++++++++++------ tests/calendar.py | 19 ---- tests/orgmode.py | 7 +- tests/takeout.py | 2 +- tests/tz.py | 95 ---------------- tox.ini | 1 - 15 files changed, 269 insertions(+), 233 deletions(-) create mode 100644 my/tests/calendar.py rename tests/location_fallback.py => my/tests/location/fallback.py (86%) rename tests/shared_config.py => my/tests/shared_tz_config.py (55%) create mode 100644 my/tests/tz.py delete mode 100644 tests/calendar.py delete mode 100644 tests/tz.py diff --git a/my/calendar/holidays.py b/my/calendar/holidays.py index f73bf70..af51696 100644 --- a/my/calendar/holidays.py +++ b/my/calendar/holidays.py @@ -19,7 +19,7 @@ def _calendar(): # todo switch to using time.tz.main once _get_tz stabilizes? from ..time.tz import via_location as LTZ # TODO would be nice to do it dynamically depending on the past timezones... - tz = LTZ._get_tz(datetime.now()) + tz = LTZ.get_tz(datetime.now()) assert tz is not None zone = tz.zone; assert zone is not None code = zone_to_countrycode(zone) diff --git a/my/core/compat.py b/my/core/compat.py index 4372a01..eccaf07 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -125,8 +125,10 @@ def test_fromisoformat() -> None: if sys.version_info[:2] >= (3, 10): from types import NoneType + from typing import TypeAlias else: NoneType = type(None) + from typing_extensions import TypeAlias if sys.version_info[:2] >= (3, 11): diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index db03c7c..79a452c 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -29,7 +29,6 @@ from typing import Iterator, List from my.core import make_logger from my.core.compat import bisect_left -from my.ip.all import ips from my.location.common import Location from my.location.fallback.common import FallbackLocation, DateExact, _datetime_timestamp @@ -37,6 +36,9 @@ logger = make_logger(__name__, level="warning") def fallback_locations() -> Iterator[FallbackLocation]: + # prefer late import since ips get overridden in tests + from my.ip.all import ips + dur = config.for_duration.total_seconds() for ip in ips(): lat, lon = ip.latlon diff --git a/my/tests/calendar.py b/my/tests/calendar.py new file mode 100644 index 0000000..b5f856c --- /dev/null +++ b/my/tests/calendar.py @@ -0,0 +1,9 @@ +from my.calendar.holidays import is_holiday + +from .shared_tz_config import config # autoused fixture + + +def test_is_holiday() -> None: + assert is_holiday('20190101') + assert not is_holiday('20180601') + assert is_holiday('20200906') # national holiday in Bulgaria diff --git a/my/tests/common.py b/my/tests/common.py index 962ee46..cf5c632 100644 --- a/my/tests/common.py +++ b/my/tests/common.py @@ -1,7 +1,5 @@ import os from pathlib import Path -import re -import sys import pytest @@ -13,20 +11,6 @@ skip_if_not_karlicoss = pytest.mark.skipif( ) -def reset_modules() -> None: - ''' - A hack to 'unload' HPI modules, otherwise some modules might cache the config - TODO: a bit crap, need a better way.. - ''' - to_unload = [m for m in sys.modules if re.match(r'my[.]?', m)] - for m in to_unload: - if 'my.pdfs' in m: - # temporary hack -- since my.pdfs migrated to a 'lazy' config, this isn't necessary anymore - # but if we reset module anyway, it confuses the ProcessPool inside my.pdfs - continue - del sys.modules[m] - - def testdata() -> Path: d = Path(__file__).absolute().parent.parent.parent / 'testdata' assert d.exists(), d diff --git a/my/tests/conftest.py b/my/tests/conftest.py index 4e67f71..cc7bb7e 100644 --- a/my/tests/conftest.py +++ b/my/tests/conftest.py @@ -1,8 +1,10 @@ import pytest + # I guess makes sense by default @pytest.fixture(autouse=True) def without_cachew(): from my.core.cachew import disabled_cachew + with disabled_cachew(): yield diff --git a/tests/location_fallback.py b/my/tests/location/fallback.py similarity index 86% rename from tests/location_fallback.py rename to my/tests/location/fallback.py index aad33ee..10a4e5b 100644 --- a/tests/location_fallback.py +++ b/my/tests/location/fallback.py @@ -2,32 +2,23 @@ To test my.location.fallback_location.all """ +from datetime import datetime, timedelta, timezone from typing import Iterator -from datetime import datetime, timezone, timedelta +import pytest from more_itertools import ilen -from my.ip.common import IP - -def data() -> Iterator[IP]: - # random IP addresses - yield IP(addr="67.98.113.0", dt=datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="67.98.112.0", dt=datetime(2020, 1, 15, 12, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="59.40.113.87", dt=datetime(2020, 2, 1, 12, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="59.40.139.87", dt=datetime(2020, 2, 1, 16, 0, 0, tzinfo=timezone.utc)) - yield IP(addr="161.235.192.228", dt=datetime(2020, 3, 1, 12, 0, 0, tzinfo=timezone.utc)) - -# redefine the my.ip.all function using data for testing import my.ip.all as ip_module -ip_module.ips = data - +from my.ip.common import IP from my.location.fallback import via_ip +from ..shared_tz_config import config # autoused fixture + + # these are all tests for the bisect algorithm defined in via_ip.py # to make sure we can correctly find IPs that are within the 'for_duration' of a given datetime - def test_ip_fallback() -> None: - # make sure that the data override works + # precondition, make sure that the data override works assert ilen(ip_module.ips()) == ilen(data()) assert ilen(ip_module.ips()) == ilen(via_ip.fallback_locations()) assert ilen(via_ip.fallback_locations()) == 5 @@ -47,7 +38,9 @@ def test_ip_fallback() -> None: assert len(est) == 1 # right after the 'for_duration' for an IP - est = list(via_ip.estimate_location(datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc) + via_ip.config.for_duration + timedelta(seconds=1))) + est = list( + via_ip.estimate_location(datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc) + via_ip.config.for_duration + timedelta(seconds=1)) + ) assert len(est) == 0 # on 2/1/2020, threes one IP if before 16:30 @@ -75,8 +68,8 @@ def test_ip_fallback() -> None: # # redefine fallback_estimators to prevent possible namespace packages the user # may have installed from having side effects testing this - from my.location.fallback import all - from my.location.fallback import via_home + from my.location.fallback import all, via_home + def _fe() -> Iterator[all.LocationEstimator]: yield via_ip.estimate_location yield via_home.estimate_location @@ -88,6 +81,7 @@ def test_ip_fallback() -> None: # # just passing via_ip should give one IP from my.location.fallback.common import _iter_estimate_from + raw_est = list(_iter_estimate_from(use_dt, (via_ip.estimate_location,))) assert len(raw_est) == 1 assert raw_est[0].datasource == "via_ip" @@ -110,7 +104,7 @@ def test_ip_fallback() -> None: # should have used the IP from via_ip since it was more accurate assert all_est.datasource == "via_ip" - # test that a home defined in shared_config.py is used if no IP is found + # test that a home defined in shared_tz_config.py is used if no IP is found loc = all.estimate_location(datetime(2021, 1, 1, 12, 30, 0, tzinfo=timezone.utc)) assert loc.datasource == "via_home" @@ -121,5 +115,21 @@ def test_ip_fallback() -> None: assert (loc.lat, loc.lon) != (bulgaria.lat, bulgaria.lon) -# re-use prepare fixture for overriding config from shared_config.py -from .tz import prepare +def data() -> Iterator[IP]: + # random IP addresses + yield IP(addr="67.98.113.0", dt=datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="67.98.112.0", dt=datetime(2020, 1, 15, 12, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="59.40.113.87", dt=datetime(2020, 2, 1, 12, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="59.40.139.87", dt=datetime(2020, 2, 1, 16, 0, 0, tzinfo=timezone.utc)) + yield IP(addr="161.235.192.228", dt=datetime(2020, 3, 1, 12, 0, 0, tzinfo=timezone.utc)) + + +@pytest.fixture(autouse=True) +def prepare(config): + before = ip_module.ips + # redefine the my.ip.all function using data for testing + ip_module.ips = data + try: + yield + finally: + ip_module.ips = before diff --git a/tests/shared_config.py b/my/tests/shared_tz_config.py similarity index 55% rename from tests/shared_config.py rename to my/tests/shared_tz_config.py index c2f6973..3d95a9e 100644 --- a/tests/shared_config.py +++ b/my/tests/shared_tz_config.py @@ -1,47 +1,26 @@ -# Defines some shared config for tests +""" +Helper to test various timezone/location dependent things +""" -from datetime import datetime, date, timezone +from datetime import date, datetime, timezone from pathlib import Path -from typing import Any, NamedTuple -import my.time.tz.via_location as LTZ +import pytest from more_itertools import one - -class SharedConfig(NamedTuple): - google: Any - location: Any - time: Any +from my.core.cfg import tmp_config -def _prepare_google_config(tmp_path: Path): - from my.tests.common import testdata - try: - track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) - except ValueError: - raise RuntimeError('testdata not found, setup git submodules?') +@pytest.fixture(autouse=True) +def config(tmp_path: Path): + # TODO could just pick a part of shared config? not sure + _takeout_path = _prepare_takeouts_dir(tmp_path) - - # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs - import zipfile - with zipfile.ZipFile(tmp_path / 'takeout.zip', 'w') as zf: - zf.writestr('Takeout/Location History/Location History.json', track.read_bytes()) - - class google_config: - takeout_path = tmp_path - return google_config - - -# pass tmp_path from pytest to this helper function -# see tests/tz.py as an example -def temp_config(temp_path: Path) -> Any: - from my.tests.common import reset_modules - reset_modules() - - LTZ.config.fast = True + class google: + takeout_path = _takeout_path class location: - home_accuracy = 30_000 + # fmt: off home = ( # supports ISO strings ('2005-12-04' , (42.697842, 23.325973)), # Bulgaria, Sofia @@ -50,16 +29,32 @@ def temp_config(temp_path: Path) -> Any: # check tz handling.. (datetime.fromtimestamp(1600000000, tz=timezone.utc), (55.7558 , 37.6173 )), # Moscow, Russia ) + # fmt: on # note: order doesn't matter, will be sorted in the data provider - class via_ip: - accuracy = 15_000 - class gpslogger: - pass class time: class tz: class via_location: - pass # just rely on the defaults... + fast = True # some tests rely on it + + with tmp_config() as cfg: + cfg.google = google + cfg.location = location + cfg.time = time + yield cfg - return SharedConfig(google=_prepare_google_config(temp_path), location=location, time=time) +def _prepare_takeouts_dir(tmp_path: Path) -> Path: + from .common import testdata + + try: + track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) + except ValueError: + raise RuntimeError('testdata not found, setup git submodules?') + + # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs + import zipfile + + with zipfile.ZipFile(tmp_path / 'takeout.zip', 'w') as zf: + zf.writestr('Takeout/Location History/Location History.json', track.read_bytes()) + return tmp_path diff --git a/my/tests/tz.py b/my/tests/tz.py new file mode 100644 index 0000000..db88278 --- /dev/null +++ b/my/tests/tz.py @@ -0,0 +1,107 @@ +import sys +from datetime import datetime, timedelta + +import pytest +import pytz + +import my.time.tz.main as tz_main +import my.time.tz.via_location as tz_via_location +from my.core import notnone +from my.core.compat import fromisoformat + +from .shared_tz_config import config # autoused fixture + + +def getzone(dt: datetime) -> str: + tz = notnone(dt.tzinfo) + return getattr(tz, 'zone') + + +@pytest.mark.parametrize('fast', [False, True]) +def test_iter_tzs(fast: bool, config) -> None: + # TODO hmm.. maybe need to make sure we start with empty config? + config.time.tz.via_location.fast = fast + + ll = list(tz_via_location._iter_tzs()) + zones = [x.zone for x in ll] + + if fast: + assert zones == [ + 'Europe/Rome', + 'Europe/Rome', + 'Europe/Vienna', + 'Europe/Vienna', + 'Europe/Vienna', + ] + else: + assert zones == [ + 'Europe/Rome', + 'Europe/Rome', + 'Europe/Ljubljana', + 'Europe/Ljubljana', + 'Europe/Ljubljana', + ] + + +def test_past() -> None: + """ + Should fallback to the 'home' location provider + """ + dt = fromisoformat('2000-01-01 12:34:45') + dt = tz_main.localize(dt) + assert getzone(dt) == 'America/New_York' + + +def test_future() -> None: + """ + For locations in the future should rely on 'home' location + """ + fut = datetime.now() + timedelta(days=100) + fut = tz_main.localize(fut) + assert getzone(fut) == 'Europe/Moscow' + + +def test_get_tz(config) -> None: + # todo hmm, the way it's implemented at the moment, never returns None? + get_tz = tz_via_location.get_tz + + # not present in the test data + tz = get_tz(fromisoformat('2020-01-01 10:00:00')) + assert notnone(tz).zone == 'Europe/Sofia' + + tz = get_tz(fromisoformat('2017-08-01 11:00:00')) + assert notnone(tz).zone == 'Europe/Vienna' + + tz = get_tz(fromisoformat('2017-07-30 10:00:00')) + assert notnone(tz).zone == 'Europe/Rome' + + tz = get_tz(fromisoformat('2020-10-01 14:15:16')) + assert tz is not None + + on_windows = sys.platform == 'win32' + if not on_windows: + tz = get_tz(datetime.min) + assert tz is not None + else: + # seems this fails because windows doesn't support same date ranges + # https://stackoverflow.com/a/41400321/ + with pytest.raises(OSError): + get_tz(datetime.min) + + +def test_policies() -> None: + naive = fromisoformat('2017-07-30 10:00:00') + assert naive.tzinfo is None # just in case + + # actual timezone at the time + assert getzone(tz_main.localize(naive)) == 'Europe/Rome' + + z = pytz.timezone('America/New_York') + aware = z.localize(naive) + + assert getzone(tz_main.localize(aware)) == 'America/New_York' + + assert getzone(tz_main.localize(aware, policy='convert')) == 'Europe/Rome' + + with pytest.raises(RuntimeError): + assert tz_main.localize(aware, policy='throw') diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index b66ff8a..329e330 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -1,52 +1,43 @@ ''' Timezone data provider, guesses timezone based on location data (e.g. GPS) ''' + REQUIRES = [ # for determining timezone by coordinate 'timezonefinder', ] +import heapq +import os from collections import Counter from dataclasses import dataclass from datetime import date, datetime from functools import lru_cache -import heapq from itertools import groupby -import os -from typing import Iterator, Optional, Tuple, Any, List, Iterable, Set, Dict +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterable, + Iterator, + List, + Optional, + Protocol, + Set, + Tuple, +) import pytz +from my.core import Stats, datetime_aware, make_logger, stat from my.core.cachew import mcachew -from my.core import make_logger, stat, Stats, datetime_aware +from my.core.compat import TypeAlias from my.core.source import import_source from my.core.warnings import high - from my.location.common import LatLon -## user might not have tz config section, so makes sense to be more defensive about it -# todo might be useful to extract a helper for this -try: - from my.config import time -except ImportError as ie: - if ie.name != 'time': - raise ie -else: - try: - user_config = time.tz.via_location - except AttributeError as ae: - if not ("'tz'" in str(ae) or "'via_location'"): - raise ae - -# deliberately dynamic to prevent confusing mypy -if 'user_config' not in globals(): - globals()['user_config'] = object -## - - -@dataclass -class config(user_config): +class config(Protocol): # less precise, but faster fast: bool = True @@ -62,6 +53,43 @@ class config(user_config): _iter_tz_refresh_time: int = 6 +def _get_user_config(): + ## user might not have tz config section, so makes sense to be more defensive about it + + class empty_config: ... + + try: + from my.config import time + except ImportError as ie: + if "'time'" not in str(ie): + raise ie + else: + return empty_config + + try: + user_config = time.tz.via_location + except AttributeError as ae: + if not ("'tz'" in str(ae) or "'via_location'" in str(ae)): + raise ae + else: + return empty_config + + return user_config + + +def make_config() -> config: + if TYPE_CHECKING: + import my.config + + user_config: TypeAlias = my.config.time.tz.via_location + else: + user_config = _get_user_config() + + class combined_config(user_config, config): ... + + return combined_config() + + logger = make_logger(__name__) @@ -78,6 +106,7 @@ def _timezone_finder(fast: bool) -> Any: # for backwards compatibility def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: try: + raise RuntimeError import my.location.all for loc in my.location.all.locations(): @@ -140,13 +169,14 @@ def _find_tz_for_locs(finder: Any, locs: Iterable[Tuple[LatLon, datetime]]) -> I # Note: this takes a while, as the upstream since _locations isn't sorted, so this # has to do an iterative sort of the entire my.locations.all list def _iter_local_dates() -> Iterator[DayWithZone]: - finder = _timezone_finder(fast=config.fast) # rely on the default + cfg = make_config() + finder = _timezone_finder(fast=cfg.fast) # rely on the default # pdt = None # TODO: warnings doesn't actually warn? # warnings = [] locs: Iterable[Tuple[LatLon, datetime]] - locs = _sorted_locations() if config.sort_locations else _locations() + locs = _sorted_locations() if cfg.sort_locations else _locations() yield from _find_tz_for_locs(finder, locs) @@ -158,11 +188,13 @@ def _iter_local_dates() -> Iterator[DayWithZone]: def _iter_local_dates_fallback() -> Iterator[DayWithZone]: from my.location.fallback.all import fallback_locations as flocs + cfg = make_config() + def _fallback_locations() -> Iterator[Tuple[LatLon, datetime]]: for loc in sorted(flocs(), key=lambda x: x.dt): yield ((loc.lat, loc.lon), loc.dt) - yield from _find_tz_for_locs(_timezone_finder(fast=config.fast), _fallback_locations()) + yield from _find_tz_for_locs(_timezone_finder(fast=cfg.fast), _fallback_locations()) def most_common(lst: Iterator[DayWithZone]) -> DayWithZone: @@ -180,7 +212,8 @@ def _iter_tz_depends_on() -> str: 2022-04-26_12 2022-04-26_18 """ - mod = config._iter_tz_refresh_time + cfg = make_config() + mod = cfg._iter_tz_refresh_time assert mod >= 1 day = str(date.today()) hr = datetime.now().hour @@ -293,5 +326,13 @@ def stats(quick: bool = False) -> Stats: return stat(localized_years) -# deprecated -- still used in some other modules so need to keep -_get_tz = get_tz +## deprecated -- keeping for now as might be used in other modules? +if not TYPE_CHECKING: + from my.core.compat import deprecated + + @deprecated('use get_tz function instead') + def _get_tz(*args, **kwargs): + return get_tz(*args, **kwargs) + + +## diff --git a/tests/calendar.py b/tests/calendar.py deleted file mode 100644 index 3435da3..0000000 --- a/tests/calendar.py +++ /dev/null @@ -1,19 +0,0 @@ -from pathlib import Path - -import pytest - -from my.calendar.holidays import is_holiday - - -def test() -> None: - assert is_holiday('20190101') - assert not is_holiday('20180601') - assert is_holiday('20200906') # national holiday in Bulgaria - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - from . import tz - # todo meh. fixtures can't be called directly? - orig = tz.prepare.__wrapped__ # type: ignore - yield from orig(tmp_path) diff --git a/tests/orgmode.py b/tests/orgmode.py index 37d783e..9b5cc59 100644 --- a/tests/orgmode.py +++ b/tests/orgmode.py @@ -1,10 +1,9 @@ from my.tests.common import skip_if_not_karlicoss as pytestmark -from my import orgmode -from my.core.orgmode import collect - - def test() -> None: + from my import orgmode + from my.core.orgmode import collect + # meh results = list(orgmode.query().collect_all(lambda n: [n] if 'python' in n.tags else [])) assert len(results) > 5 diff --git a/tests/takeout.py b/tests/takeout.py index cddc684..47d405b 100644 --- a/tests/takeout.py +++ b/tests/takeout.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +from my.tests.common import skip_if_not_karlicoss as pytestmark from datetime import datetime, timezone from itertools import islice import pytz diff --git a/tests/tz.py b/tests/tz.py deleted file mode 100644 index d86c5cb..0000000 --- a/tests/tz.py +++ /dev/null @@ -1,95 +0,0 @@ -import sys -from datetime import datetime, timedelta -from pathlib import Path - -import pytest -import pytz - -from my.core.error import notnone - -import my.time.tz.main as TZ -import my.time.tz.via_location as LTZ - - -def test_iter_tzs() -> None: - ll = list(LTZ._iter_tzs()) - assert len(ll) > 3 - - -def test_past() -> None: - # should fallback to the home location provider - dt = D('20000101 12:34:45') - dt = TZ.localize(dt) - tz = dt.tzinfo - assert tz is not None - assert getattr(tz, 'zone') == 'America/New_York' - - -def test_future() -> None: - fut = datetime.now() + timedelta(days=100) - # shouldn't crash at least - assert TZ.localize(fut) is not None - - -def test_tz() -> None: - # todo hmm, the way it's implemented at the moment, never returns None? - - # not present in the test data - tz = LTZ._get_tz(D('20200101 10:00:00')) - assert notnone(tz).zone == 'Europe/Sofia' - - tz = LTZ._get_tz(D('20170801 11:00:00')) - assert notnone(tz).zone == 'Europe/Vienna' - - tz = LTZ._get_tz(D('20170730 10:00:00')) - assert notnone(tz).zone == 'Europe/Rome' - - tz = LTZ._get_tz(D('20201001 14:15:16')) - assert tz is not None - - on_windows = sys.platform == 'win32' - if not on_windows: - tz = LTZ._get_tz(datetime.min) - assert tz is not None - else: - # seems this fails because windows doesn't support same date ranges - # https://stackoverflow.com/a/41400321/ - with pytest.raises(OSError): - LTZ._get_tz(datetime.min) - - -def test_policies() -> None: - getzone = lambda dt: getattr(dt.tzinfo, 'zone') - - naive = D('20170730 10:00:00') - # actual timezone at the time - assert getzone(TZ.localize(naive)) == 'Europe/Rome' - - z = pytz.timezone('America/New_York') - aware = z.localize(naive) - - assert getzone(TZ.localize(aware)) == 'America/New_York' - - assert getzone(TZ.localize(aware, policy='convert')) == 'Europe/Rome' - - - with pytest.raises(RuntimeError): - assert TZ.localize(aware, policy='throw') - - -def D(dstr: str) -> datetime: - return datetime.strptime(dstr, '%Y%m%d %H:%M:%S') - - - -@pytest.fixture(autouse=True) -def prepare(tmp_path: Path): - from .shared_config import temp_config - conf = temp_config(tmp_path) - - import my.core.cfg as C - with C.tmp_config() as config: - config.google = conf.google - config.time = conf.time - config.location = conf.location - yield diff --git a/tox.ini b/tox.ini index 248469e..20f730b 100644 --- a/tox.ini +++ b/tox.ini @@ -88,7 +88,6 @@ commands = {envpython} -m pytest tests \ # ignore some tests which might take a while to run on ci.. - --ignore tests/takeout.py \ --ignore tests/extra/polar.py {posargs} From b87d1c970a870eda11cc48f45d074c286dae15e6 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 03:34:45 +0100 Subject: [PATCH 12/55] tests: move remaining tests from tests/ to my.tests, cleanup corresponding modules --- my/body/weight.py | 35 ++++++++---- my/orgmode.py | 36 ++++++++---- my/pdfs.py | 8 +-- {tests => my/tests}/bluemaestro.py | 12 ++-- my/tests/body/weight.py | 57 +++++++++++++++++++ {tests => my/tests}/pdfs.py | 3 +- my/tests/reddit.py | 9 +-- tests/config.py | 89 ------------------------------ tox.ini | 5 -- 9 files changed, 120 insertions(+), 134 deletions(-) rename {tests => my/tests}/bluemaestro.py (86%) create mode 100644 my/tests/body/weight.py rename {tests => my/tests}/pdfs.py (99%) delete mode 100644 tests/config.py diff --git a/my/body/weight.py b/my/body/weight.py index def3e87..277b4d1 100644 --- a/my/body/weight.py +++ b/my/body/weight.py @@ -2,21 +2,29 @@ Weight data (manually logged) ''' +from dataclasses import dataclass from datetime import datetime -from typing import NamedTuple, Iterator +from typing import Any, Iterator -from ..core import LazyLogger -from ..core.error import Res, set_error_datetime, extract_error_datetime +from my.core import make_logger +from my.core.error import Res, extract_error_datetime, set_error_datetime -from .. import orgmode +from my import orgmode -from my.config import weight as config # type: ignore[attr-defined] +config = Any -log = LazyLogger('my.body.weight') +def make_config() -> config: + from my.config import weight as user_config # type: ignore[attr-defined] + + return user_config() -class Entry(NamedTuple): +log = make_logger(__name__) + + +@dataclass +class Entry: dt: datetime value: float # TODO comment?? @@ -26,6 +34,8 @@ Result = Res[Entry] def from_orgmode() -> Iterator[Result]: + cfg = make_config() + orgs = orgmode.query() for o in orgmode.query().all(): if 'weight' not in o.tags: @@ -46,8 +56,8 @@ def from_orgmode() -> Iterator[Result]: yield e continue # FIXME use timezone provider - created = config.default_timezone.localize(created) - assert created is not None #??? somehow mypy wasn't happy? + created = cfg.default_timezone.localize(created) + assert created is not None # ??? somehow mypy wasn't happy? yield Entry( dt=created, value=w, @@ -57,19 +67,21 @@ def from_orgmode() -> Iterator[Result]: def make_dataframe(data: Iterator[Result]): import pandas as pd + def it(): for e in data: if isinstance(e, Exception): dt = extract_error_datetime(e) yield { - 'dt' : dt, + 'dt': dt, 'error': str(e), } else: yield { - 'dt' : e.dt, + 'dt': e.dt, 'weight': e.value, } + df = pd.DataFrame(it()) df.set_index('dt', inplace=True) # TODO not sure about UTC?? @@ -81,6 +93,7 @@ def dataframe(): entries = from_orgmode() return make_dataframe(entries) + # TODO move to a submodule? e.g. my.body.weight.orgmode? # so there could be more sources # not sure about my.body thing though diff --git a/my/orgmode.py b/my/orgmode.py index c27f5a7..cf14e43 100644 --- a/my/orgmode.py +++ b/my/orgmode.py @@ -6,18 +6,28 @@ REQUIRES = [ 'orgparse', ] +import re from datetime import datetime from pathlib import Path -import re -from typing import List, Sequence, Iterable, NamedTuple, Optional, Tuple +from typing import Iterable, List, NamedTuple, Optional, Sequence, Tuple -from my.core import get_files +import orgparse + +from my.core import Paths, Stats, get_files, stat from my.core.cachew import cache_dir, mcachew from my.core.orgmode import collect -from my.config import orgmode as user_config -import orgparse +class config: + paths: Paths + + +def make_config() -> config: + from my.config import orgmode as user_config + + class combined_config(user_config, config): ... + + return combined_config() # temporary? hack to cache org-mode notes @@ -28,10 +38,13 @@ class OrgNote(NamedTuple): def inputs() -> Sequence[Path]: - return get_files(user_config.paths) + cfg = make_config() + return get_files(cfg.paths) _rgx = re.compile(orgparse.date.gene_timestamp_regex(brtype='inactive'), re.VERBOSE) + + def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: heading = n.heading # meh.. support in orgparse? @@ -41,7 +54,7 @@ def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: # try to guess from heading m = _rgx.search(heading) if m is not None: - createds = m.group(0) # could be None + createds = m.group(0) # could be None if createds is None: return (None, heading) assert isinstance(createds, str) @@ -67,7 +80,7 @@ def to_note(x: orgparse.OrgNode) -> OrgNote: created = None return OrgNote( created=created, - heading=heading, # todo include the body? + heading=heading, # todo include the body? tags=list(x.tags), ) @@ -84,14 +97,15 @@ def _cachew_cache_path(_self, f: Path) -> Path: def _cachew_depends_on(_self, f: Path): return (f, f.stat().st_mtime) - + class Query: def __init__(self, files: Sequence[Path]) -> None: self.files = files # TODO yield errors? @mcachew( - cache_path=_cachew_cache_path, force_file=True, + cache_path=_cachew_cache_path, + force_file=True, depends_on=_cachew_depends_on, ) def _iterate(self, f: Path) -> Iterable[OrgNote]: @@ -114,8 +128,8 @@ def query() -> Query: return Query(files=inputs()) -from my.core import Stats, stat def stats() -> Stats: def outlines(): return query().all() + return stat(outlines) diff --git a/my/pdfs.py b/my/pdfs.py index 524c68b..1cedfd5 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -10,7 +10,7 @@ REQUIRES = [ import time from datetime import datetime from pathlib import Path -from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence +from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence, TYPE_CHECKING import pdfannots from more_itertools import bucket @@ -185,8 +185,6 @@ def stats() -> Stats: ### legacy/misc stuff -iter_annotations = annotations # for backwards compatibility +if not TYPE_CHECKING: + iter_annotations = annotations ### - -# can use 'hpi query my.pdfs.annotations -o pprint' to test -# diff --git a/tests/bluemaestro.py b/my/tests/bluemaestro.py similarity index 86% rename from tests/bluemaestro.py rename to my/tests/bluemaestro.py index 63ce589..2d7c81e 100644 --- a/tests/bluemaestro.py +++ b/my/tests/bluemaestro.py @@ -1,12 +1,12 @@ -from pathlib import Path from typing import Iterator +import pytest from more_itertools import one -import pytest +from my.bluemaestro import Measurement, measurements +from my.core.cfg import tmp_config - -from my.bluemaestro import measurements, Measurement +from .common import testdata def ok_measurements() -> Iterator[Measurement]: @@ -26,7 +26,7 @@ def test() -> None: # check that timezone is set properly assert dts == '20200824 22' - assert len(tp) == 1 # should be unique + assert len(tp) == 1 # should be unique # 2.5 K + 4 K datapoints, somewhat overlapping assert len(res2020) < 6000 @@ -46,14 +46,12 @@ def test_old_db() -> None: @pytest.fixture(autouse=True) def prepare(): - from my.tests.common import testdata bmdata = testdata() / 'hpi-testdata' / 'bluemaestro' assert bmdata.exists(), bmdata class bluemaestro: export_path = bmdata - from my.core.cfg import tmp_config with tmp_config() as config: config.bluemaestro = bluemaestro yield diff --git a/my/tests/body/weight.py b/my/tests/body/weight.py new file mode 100644 index 0000000..069e940 --- /dev/null +++ b/my/tests/body/weight.py @@ -0,0 +1,57 @@ +from pathlib import Path +import pytz +from my.core.cfg import tmp_config +import pytest +from my.body.weight import from_orgmode + + +def test_body_weight() -> None: + weights = [0.0 if isinstance(x, Exception) else x.value for x in from_orgmode()] + + assert weights == [ + 0.0, + 62.0, + 0.0, + 61.0, + 62.0, + 0.0, + ] + + +@pytest.fixture(autouse=True) +def prepare(tmp_path: Path): + ndir = tmp_path / 'notes' + ndir.mkdir() + logs = ndir / 'logs.org' + logs.write_text( + ''' +#+TITLE: Stuff I'm logging + +* Weight (org-capture) :weight: +** [2020-05-01 Fri 09:00] 62 +** 63 + this should be ignored, got no timestamp +** [2020-05-03 Sun 08:00] 61 +** [2020-05-04 Mon 10:00] 62 +''' + ) + misc = ndir / 'misc.org' + misc.write_text( + ''' +Some misc stuff + +* unrelated note :weight:whatever: +''' + ) + + class orgmode: + paths = [ndir] + + class weight: + # TODO ugh. this belongs to tz provider or global config or something + default_timezone = pytz.timezone('Europe/London') + + with tmp_config() as cfg: + cfg.orgmode = orgmode + cfg.weight = weight + yield diff --git a/tests/pdfs.py b/my/tests/pdfs.py similarity index 99% rename from tests/pdfs.py rename to my/tests/pdfs.py index 6db669f..bd1e93a 100644 --- a/tests/pdfs.py +++ b/my/tests/pdfs.py @@ -5,9 +5,8 @@ import pytest from more_itertools import ilen from my.core.cfg import tmp_config -from my.tests.common import testdata - from my.pdfs import annotated_pdfs, annotations, get_annots +from my.tests.common import testdata def test_module(with_config) -> None: diff --git a/my/tests/reddit.py b/my/tests/reddit.py index fb8d6d2..4f1ec51 100644 --- a/my/tests/reddit.py +++ b/my/tests/reddit.py @@ -1,15 +1,16 @@ +import pytest +from more_itertools import consume + from my.core.cfg import tmp_config from my.core.utils.itertools import ensure_unique -# todo ugh, it's discovered as a test??? from .common import testdata -from more_itertools import consume -import pytest # deliberately use mixed style imports on the top level and inside the methods to test tmp_config stuff -import my.reddit.rexport as my_reddit_rexport +# todo won't really be necessary once we migrate to lazy user config import my.reddit.all as my_reddit_all +import my.reddit.rexport as my_reddit_rexport def test_basic_1() -> None: diff --git a/tests/config.py b/tests/config.py deleted file mode 100644 index acfe1f1..0000000 --- a/tests/config.py +++ /dev/null @@ -1,89 +0,0 @@ -from pathlib import Path - - -# TODO move this somewhere else -- there are more specific tests covering this now -def test_dynamic_configuration(notes: Path) -> None: - import pytz - from types import SimpleNamespace as NS - - from my.core.cfg import tmp_config - with tmp_config() as C: - C.orgmode = NS(paths=[notes]) - # TODO ugh. this belongs to tz provider or global config or something - C.weight = NS(default_timezone=pytz.timezone('Europe/London')) - - from my.body.weight import from_orgmode - weights = [0.0 if isinstance(x, Exception) else x.value for x in from_orgmode()] - - assert weights == [ - 0.0, - 62.0, - 0.0, - 61.0, - 62.0, - 0.0, - ] - -import pytest - - - -from dataclasses import dataclass - - -# TODO this test should probs be deprecated? it's more of a documentation? -def test_user_config() -> None: - from my.core.common import classproperty - class user_config: - param1 = 'abacaba' - # TODO fuck. properties don't work here??? - @classproperty - def param2(cls) -> int: - return 456 - - extra = 'extra!' - - @dataclass - class test_config(user_config): - param1: str - param2: int # type: ignore[assignment] # TODO need to figure out how to trick mypy for @classproperty - param3: str = 'default' - - assert test_config.param1 == 'abacaba' - assert test_config.param2 == 456 - assert test_config.param3 == 'default' - assert test_config.extra == 'extra!' - - from my.core.cfg import make_config - c = make_config(test_config) - assert c.param1 == 'abacaba' - assert c.param2 == 456 - assert c.param3 == 'default' - assert c.extra == 'extra!' - - -@pytest.fixture -def notes(tmp_path: Path): - ndir = tmp_path / 'notes' - ndir.mkdir() - logs = ndir / 'logs.org' - logs.write_text(''' -#+TITLE: Stuff I'm logging - -* Weight (org-capture) :weight: -** [2020-05-01 Fri 09:00] 62 -** 63 - this should be ignored, got no timestamp -** [2020-05-03 Sun 08:00] 61 -** [2020-05-04 Mon 10:00] 62 - ''') - misc = ndir / 'misc.org' - misc.write_text(''' -Some misc stuff - -* unrelated note :weight:whatever: - ''') - try: - yield ndir - finally: - pass diff --git a/tox.ini b/tox.ini index 20f730b..6b95088 100644 --- a/tox.ini +++ b/tox.ini @@ -86,11 +86,6 @@ commands = --pyargs {[testenv]package_name}.core {[testenv]package_name}.tests \ {posargs} - {envpython} -m pytest tests \ - # ignore some tests which might take a while to run on ci.. - --ignore tests/extra/polar.py - {posargs} - [testenv:demo] commands = From b1fe23b8d0d2ede92c4c17c7199f537c0523317b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 26 Aug 2024 03:50:32 +0100 Subject: [PATCH 13/55] my.rss.feedly/my.twittr.talon -- migrate to use lazy user configs --- my/rss/feedly.py | 28 ++++++++++++++++++++++------ my/twitter/talon.py | 34 ++++++++++++++++++++++++---------- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/my/rss/feedly.py b/my/rss/feedly.py index 55bcf9b..127ef61 100644 --- a/my/rss/feedly.py +++ b/my/rss/feedly.py @@ -2,19 +2,35 @@ Feedly RSS reader """ -from my.config import feedly as config - -from datetime import datetime, timezone import json +from abc import abstractmethod +from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Sequence +from typing import Iterator, Protocol, Sequence + +from my.core import Paths, get_files -from my.core import get_files from .common import Subscription, SubscriptionState +class config(Protocol): + @property + @abstractmethod + def export_path(self) -> Paths: + raise NotImplementedError + + +def make_config() -> config: + from my.config import feedly as user_config + + class combined_config(user_config, config): ... + + return combined_config() + + def inputs() -> Sequence[Path]: - return get_files(config.export_path) + cfg = make_config() + return get_files(cfg.export_path) def parse_file(f: Path) -> Iterator[Subscription]: diff --git a/my/twitter/talon.py b/my/twitter/talon.py index 306a735..1b79727 100644 --- a/my/twitter/talon.py +++ b/my/twitter/talon.py @@ -1,12 +1,15 @@ """ Twitter data from Talon app database (in =/data/data/com.klinker.android.twitter_l/databases/=) """ + from __future__ import annotations -from dataclasses import dataclass -from datetime import datetime, timezone import re import sqlite3 +from abc import abstractmethod +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path from typing import Iterator, Sequence, Union from my.core import Paths, Res, datetime_aware, get_files @@ -15,18 +18,25 @@ from my.core.sqlite import sqlite_connection from .common import TweetId, permalink -from my.config import twitter as user_config + +class config: + @property + @abstractmethod + def export_path(self) -> Paths: + raise NotImplementedError -@dataclass -class config(user_config.talon): - # paths[s]/glob to the exported sqlite databases - export_path: Paths +def make_config() -> config: + from my.config import twitter as user_config + + class combined_config(user_config.talon, config): + pass + + return combined_config() -from pathlib import Path def inputs() -> Sequence[Path]: - return get_files(config.export_path) + return get_files(make_config().export_path) @dataclass(unsafe_hash=True) @@ -46,12 +56,16 @@ class Tweet: @dataclass(unsafe_hash=True) class _IsTweet: tweet: Tweet + + @dataclass(unsafe_hash=True) class _IsFavorire: tweet: Tweet Entity = Union[_IsTweet, _IsFavorire] + + def _entities() -> Iterator[Res[Entity]]: for f in inputs(): yield from _process_one(f) @@ -59,7 +73,7 @@ def _entities() -> Iterator[Res[Entity]]: def _process_one(f: Path) -> Iterator[Res[Entity]]: handlers = { - 'user_tweets.db' : _process_user_tweets, + 'user_tweets.db': _process_user_tweets, 'favorite_tweets.db': _process_favorite_tweets, } fname = f.name From c08ddbc781b4cc79441e9d0d856957a94791fb7f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 21:02:39 +0100 Subject: [PATCH 14/55] general: small updates for typing while trying out pyright --- my/core/common.py | 2 +- my/core/stats.py | 2 +- my/core/util.py | 2 +- my/core/utils/itertools.py | 8 +++----- my/google/takeout/html.py | 5 ++--- my/hypothesis.py | 5 +++-- my/smscalls.py | 2 +- 7 files changed, 12 insertions(+), 14 deletions(-) diff --git a/my/core/common.py b/my/core/common.py index dcd1074..d0b737e 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -133,8 +133,8 @@ def test_classproperty() -> None: return 'hello' res = C.prop - assert res == 'hello' assert_type(res, str) + assert res == 'hello' # hmm, this doesn't really work with mypy well.. diff --git a/my/core/stats.py b/my/core/stats.py index 08821a2..bfedbd2 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -2,7 +2,7 @@ Helpers for hpi doctor/stats functionality. ''' -import collections +import collections.abc import importlib import inspect import typing diff --git a/my/core/util.py b/my/core/util.py index b48a450..0c596fa 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -25,7 +25,7 @@ def is_not_hpi_module(module: str) -> Optional[str]: ''' None if a module, otherwise returns reason ''' - import importlib + import importlib.util path: Optional[str] = None try: diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 023484d..66f82bd 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -275,20 +275,18 @@ def test_check_if_hashable() -> None: x1: List[int] = [1, 2] r1 = check_if_hashable(x1) - # tgype: ignore[comparison-overlap] # object should be unchanged - assert r1 is x1 assert_type(r1, Iterable[int]) + assert r1 is x1 x2: Iterator[Union[int, str]] = iter((123, 'aba')) r2 = check_if_hashable(x2) - assert list(r2) == [123, 'aba'] assert_type(r2, Iterable[Union[int, str]]) + assert list(r2) == [123, 'aba'] x3: Tuple[object, ...] = (789, 'aba') r3 = check_if_hashable(x3) - # ttype: ignore[comparison-overlap] # object should be unchanged - assert r3 is x3 assert_type(r3, Iterable[object]) + assert r3 is x3 # object should be unchanged x4: List[Set[int]] = [{1, 2, 3}, {4, 5, 6}] with pytest.raises(Exception): diff --git a/my/google/takeout/html.py b/my/google/takeout/html.py index d393957..3ce692c 100644 --- a/my/google/takeout/html.py +++ b/my/google/takeout/html.py @@ -8,7 +8,6 @@ from pathlib import Path from datetime import datetime from html.parser import HTMLParser from typing import List, Optional, Any, Callable, Iterable, Tuple -from collections import OrderedDict from urllib.parse import unquote import pytz @@ -94,8 +93,8 @@ class TakeoutHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): if self.state == State.INSIDE and tag == 'a': self.state = State.PARSING_LINK - attrs = OrderedDict(attrs) - hr = attrs['href'] + [hr] = (v for k, v in attrs if k == 'href') + assert hr is not None # sometimes it's starts with this prefix, it's apparently clicks from google search? or visits from chrome address line? who knows... # TODO handle http? diff --git a/my/hypothesis.py b/my/hypothesis.py index 55fff64..82104cd 100644 --- a/my/hypothesis.py +++ b/my/hypothesis.py @@ -41,6 +41,7 @@ except ModuleNotFoundError as e: dal = pre_pip_dal_handler('hypexport', e, config, requires=REQUIRES) +DAL = dal.DAL Highlight = dal.Highlight Page = dal.Page @@ -49,8 +50,8 @@ def inputs() -> Sequence[Path]: return get_files(config.export_path) -def _dal() -> dal.DAL: - return dal.DAL(inputs()) +def _dal() -> DAL: + return DAL(inputs()) # TODO they are in reverse chronological order... diff --git a/my/smscalls.py b/my/smscalls.py index f436709..b56026d 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -24,7 +24,7 @@ from datetime import datetime, timezone from pathlib import Path from typing import NamedTuple, Iterator, Set, Tuple, Optional, Any, Dict, List -from lxml import etree +import lxml.etree as etree from my.core.error import Res From d244c7cc4e17bc9010829c34dd4b88aaba5e5981 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 22:50:37 +0100 Subject: [PATCH 15/55] ruff: enable and fix C4 ruleset --- my/coding/commits.py | 4 ++-- my/core/_deprecated/kompress.py | 2 +- my/core/common.py | 2 +- my/core/freezer.py | 6 ++++-- my/core/influxdb.py | 12 ++++++------ my/core/pandas.py | 2 +- my/core/query.py | 10 +++++----- my/core/sqlite.py | 2 +- my/emfit/__init__.py | 2 +- my/github/gdpr.py | 4 ++-- my/lastfm.py | 9 +++++---- my/location/fallback/via_home.py | 2 +- my/media/imdb.py | 2 +- my/pdfs.py | 2 +- my/rescuetime.py | 13 +++++++------ my/tests/pdfs.py | 2 +- my/twitter/archive.py | 2 +- my/youtube/takeout.py | 2 +- ruff.toml | 6 ++++++ 19 files changed, 48 insertions(+), 38 deletions(-) diff --git a/my/coding/commits.py b/my/coding/commits.py index dac3b1f..20b66a0 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -161,14 +161,14 @@ def git_repos_in(roots: List[Path]) -> List[Path]: *roots, ]).decode('utf8').splitlines() - candidates = set(Path(o).resolve().absolute().parent for o in outputs) + candidates = {Path(o).resolve().absolute().parent for o in outputs} # exclude stuff within .git dirs (can happen for submodules?) candidates = {c for c in candidates if '.git' not in c.parts[:-1]} candidates = {c for c in candidates if is_git_dir(c)} - repos = list(sorted(map(_git_root, candidates))) + repos = sorted(map(_git_root, candidates)) return repos diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 7eb9b37..89e5745 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -244,7 +244,7 @@ class ZipPath(zipfile_Path): # see https://en.wikipedia.org/wiki/ZIP_(file_format)#Structure dt = datetime(*self.root.getinfo(self.at).date_time) ts = int(dt.timestamp()) - params = dict( + params = dict( # noqa: C408 st_mode=0, st_ino=0, st_dev=0, diff --git a/my/core/common.py b/my/core/common.py index d0b737e..ba4ce6b 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -80,7 +80,7 @@ def get_files( paths.append(src) if sort: - paths = list(sorted(paths)) + paths = sorted(paths) if len(paths) == 0: # todo make it conditionally defensive based on some global settings diff --git a/my/core/freezer.py b/my/core/freezer.py index e46525b..93bceb7 100644 --- a/my/core/freezer.py +++ b/my/core/freezer.py @@ -60,8 +60,10 @@ class _A: def test_freezer() -> None: - - val = _A(x=dict(an_int=123, an_any=[1, 2, 3])) + val = _A(x={ + 'an_int': 123, + 'an_any': [1, 2, 3], + }) af = Freezer(_A) fval = af.freeze(val) diff --git a/my/core/influxdb.py b/my/core/influxdb.py index c39f6af..b1d6b9b 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -72,16 +72,16 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c fields = filter_dict(d) - yield dict( - measurement=measurement, + yield { + 'measurement': measurement, # TODO maybe good idea to tag with database file/name? to inspect inconsistencies etc.. # hmm, so tags are autoindexed and might be faster? # not sure what's the big difference though # "fields are data and tags are metadata" - tags=tags, - time=dt, - fields=fields, - ) + 'tags': tags, + 'time': dt, + 'fields': fields, + } from more_itertools import chunked # "The optimal batch size is 5000 lines of line protocol." diff --git a/my/core/pandas.py b/my/core/pandas.py index 8ad93cb..d38465a 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -222,7 +222,7 @@ def test_as_dataframe() -> None: from .compat import fromisoformat - it = (dict(i=i, s=f'str{i}') for i in range(5)) + it = ({'i': i, 's': f'str{i}'} for i in range(5)) with pytest.warns(UserWarning, match=r"No 'error' column") as record_warnings: # noqa: F841 df: DataFrameT = as_dataframe(it) # todo test other error col policies diff --git a/my/core/query.py b/my/core/query.py index cf85b1b..54cd9db 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -655,7 +655,7 @@ def test_wrap_unsortable() -> None: # by default, wrap unsortable res = list(select(_mixed_iter(), order_key="z")) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 2}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 2}) def test_disabled_wrap_unsorted() -> None: @@ -674,7 +674,7 @@ def test_drop_unsorted() -> None: # test drop unsortable, should remove them before the 'sorted' call res = list(select(_mixed_iter(), order_key="z", wrap_unsorted=False, drop_unsorted=True)) assert len(res) == 4 - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4}) def test_drop_exceptions() -> None: @@ -705,7 +705,7 @@ def test_wrap_unsortable_with_error_and_warning() -> None: # by default should wrap unsortable (error) with pytest.warns(UserWarning, match=r"encountered exception"): res = list(select(_mixed_iter_errors(), order_value=lambda o: isinstance(o, datetime))) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "_B": 2, "Unsortable": 1}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "_B": 2, "Unsortable": 1}) # compare the returned error wrapped in the Unsortable returned_error = next((o for o in res if isinstance(o, Unsortable))).obj assert "Unhandled error!" == str(returned_error) @@ -717,7 +717,7 @@ def test_order_key_unsortable() -> None: # both unsortable and items which dont match the order_by (order_key) in this case should be classified unsorted res = list(select(_mixed_iter_errors(), order_key="z")) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 3}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 3}) def test_order_default_param() -> None: @@ -737,7 +737,7 @@ def test_no_recursive_unsortables() -> None: # select to select as input, wrapping unsortables the first time, second should drop them # reverse=True to send errors to the end, so the below order_key works res = list(select(_mixed_iter_errors(), order_key="z", reverse=True)) - assert Counter(map(lambda t: type(t).__name__, res)) == Counter({"_A": 4, "Unsortable": 3}) + assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "Unsortable": 3}) # drop_unsorted dropped = list(select(res, order_key="z", drop_unsorted=True)) diff --git a/my/core/sqlite.py b/my/core/sqlite.py index 47bd78b..08a80e5 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -35,7 +35,7 @@ SqliteRowFactory = Callable[[sqlite3.Cursor, sqlite3.Row], Any] def dict_factory(cursor, row): fields = [column[0] for column in cursor.description] - return {key: value for key, value in zip(fields, row)} + return dict(zip(fields, row)) Factory = Union[SqliteRowFactory, Literal['row', 'dict']] diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 7fae8ea..71a483f 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -189,7 +189,7 @@ def fake_data(nights: int = 500) -> Iterator: # TODO remove/deprecate it? I think used by timeline def get_datas() -> List[Emfit]: # todo ugh. run lint properly - return list(sorted(datas(), key=lambda e: e.start)) # type: ignore + return sorted(datas(), key=lambda e: e.start) # type: ignore # TODO move away old entries if there is a diff?? diff --git a/my/github/gdpr.py b/my/github/gdpr.py index 1fde7c9..4ca8e84 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -51,12 +51,12 @@ def events() -> Iterable[Res[Event]]: # a bit naughty and ad-hoc, but we will generify reading from tar.gz. once we have more examples # another one is zulip archive if last.is_dir(): - files = list(sorted(last.glob('*.json'))) # looks like all files are in the root + files = sorted(last.glob('*.json')) # looks like all files are in the root open_file = lambda f: f.open() else: # treat as .tar.gz tfile = tarfile.open(last) - files = list(sorted(map(Path, tfile.getnames()))) + files = sorted(map(Path, tfile.getnames())) files = [p for p in files if len(p.parts) == 1 and p.suffix == '.json'] open_file = lambda p: notnone(tfile.extractfile(f'./{p}')) # NOTE odd, doesn't work without ./ diff --git a/my/lastfm.py b/my/lastfm.py index 6618738..d20ebf3 100644 --- a/my/lastfm.py +++ b/my/lastfm.py @@ -83,9 +83,10 @@ def stats() -> Stats: def fill_influxdb() -> None: from my.core import influxdb + # todo needs to be more automatic - sd = (dict( - dt=x.dt, - track=x.track, - ) for x in scrobbles()) + sd = ({ + 'dt': x.dt, + 'track': x.track, + } for x in scrobbles()) influxdb.fill(sd, measurement=__name__) diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py index 259dcaa..199ebb0 100644 --- a/my/location/fallback/via_home.py +++ b/my/location/fallback/via_home.py @@ -55,7 +55,7 @@ class Config(user_config): if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) res.append((dt, loc)) - res = list(sorted(res, key=lambda p: p[0])) + res = sorted(res, key=lambda p: p[0]) return res diff --git a/my/media/imdb.py b/my/media/imdb.py index b7ecbde..df6d62d 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -33,7 +33,7 @@ def iter_movies() -> Iterator[Movie]: def get_movies() -> List[Movie]: - return list(sorted(iter_movies(), key=lambda m: m.created)) + return sorted(iter_movies(), key=lambda m: m.created) def test(): diff --git a/my/pdfs.py b/my/pdfs.py index 1cedfd5..db49c0e 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -97,7 +97,7 @@ def get_annots(p: Path) -> List[Annotation]: b = time.time() with p.open('rb') as fo: doc = pdfannots.process_file(fo, emit_progress_to=None) - annots = [a for a in doc.iter_annots()] + annots = list(doc.iter_annots()) # also has outlines are kinda like TOC, I don't really need them a = time.time() took = a - b diff --git a/my/rescuetime.py b/my/rescuetime.py index c493e8e..76a0d4c 100644 --- a/my/rescuetime.py +++ b/my/rescuetime.py @@ -82,12 +82,13 @@ def fake_data(rows: int=1000) -> Iterator: def fill_influxdb() -> None: - from .core import influxdb - it = (dict( - dt=e.dt, - duration_d=e.duration_s, - tags=dict(activity=e.activity), - ) for e in entries() if isinstance(e, Entry)) # TODO handle errors in core.influxdb + from my.core import influxdb + + it = ({ + 'dt': e.dt, + 'duration_d': e.duration_s, + 'tags': {'activity': e.activity}, + } for e in entries() if isinstance(e, Entry)) # TODO handle errors in core.influxdb influxdb.fill(it, measurement=__name__) diff --git a/my/tests/pdfs.py b/my/tests/pdfs.py index bd1e93a..3702424 100644 --- a/my/tests/pdfs.py +++ b/my/tests/pdfs.py @@ -62,7 +62,7 @@ def test_get_annots() -> None: """ annotations = get_annots(testdata() / 'pdfs' / 'Information Architecture for the World Wide Web.pdf') assert len(annotations) == 3 - assert set([a.highlight for a in annotations]) == EXPECTED_HIGHLIGHTS + assert {a.highlight for a in annotations} == EXPECTED_HIGHLIGHTS def test_annotated_pdfs_with_filelist() -> None: diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 0ea6b24..685f7fc 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -105,7 +105,7 @@ class Tweet: repls.append((fr, to, me['display_url'])) # todo not sure, maybe use media_url_https instead? # for now doing this for compatibility with twint - repls = list(sorted(repls)) + repls = sorted(repls) parts = [] idx = 0 for fr, to, what in repls: diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 8fe8f2c..99d65d9 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -120,4 +120,4 @@ def _watched_legacy() -> Iterable[Watched]: watches.append(Watched(url=url, title=title, when=dt)) # todo hmm they already come sorted.. wonder if should just rely on it.. - return list(sorted(watches, key=lambda e: e.when)) + return sorted(watches, key=lambda e: e.when) diff --git a/ruff.toml b/ruff.toml index 54f621c..db926da 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,3 +1,9 @@ +lint.extend-select = [ + "F", # flakes rules -- default, but extend just in case + "E", # pycodestyle -- default, but extend just in case + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls +] + lint.ignore = [ ### too opinionated style checks "E501", # too long lines From 118c2d44849b4df661cf07a91d690e91ec1a6069 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 23:12:57 +0100 Subject: [PATCH 16/55] ruff: enable UP ruleset for detecting python deprecations --- my/core/__main__.py | 4 ++-- my/core/_deprecated/kompress.py | 10 ++-------- my/core/query.py | 2 +- my/core/query_range.py | 3 +-- my/core/stats.py | 13 +++++++++---- my/core/tests/denylist.py | 3 +-- my/core/util.py | 3 +-- my/time/tz/via_location.py | 2 +- ruff.toml | 9 +++++++++ 9 files changed, 27 insertions(+), 22 deletions(-) diff --git a/my/core/__main__.py b/my/core/__main__.py index 276de26..986b05f 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -16,7 +16,7 @@ from typing import Any, Callable, Iterable, List, Optional, Sequence, Type import click -@functools.lru_cache() +@functools.lru_cache def mypy_cmd() -> Optional[Sequence[str]]: try: # preferably, use mypy from current python env @@ -43,7 +43,7 @@ def run_mypy(cfg_path: Path) -> Optional[CompletedProcess]: cmd = mypy_cmd() if cmd is None: return None - mres = run([ + mres = run([ # noqa: UP022 *cmd, '--namespace-packages', '--color-output', # not sure if works?? diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 89e5745..803e515 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -148,14 +148,8 @@ def kexists(path: PathIsh, subpath: str) -> bool: import zipfile -if sys.version_info[:2] >= (3, 8): - # meh... zipfile.Path is not available on 3.7 - zipfile_Path = zipfile.Path -else: - if typing.TYPE_CHECKING: - zipfile_Path = Any - else: - zipfile_Path = object +# meh... zipfile.Path is not available on 3.7 +zipfile_Path = zipfile.Path @total_ordering diff --git a/my/core/query.py b/my/core/query.py index 54cd9db..bc7e222 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -707,7 +707,7 @@ def test_wrap_unsortable_with_error_and_warning() -> None: res = list(select(_mixed_iter_errors(), order_value=lambda o: isinstance(o, datetime))) assert Counter(type(t).__name__ for t in res) == Counter({"_A": 4, "_B": 2, "Unsortable": 1}) # compare the returned error wrapped in the Unsortable - returned_error = next((o for o in res if isinstance(o, Unsortable))).obj + returned_error = next(o for o in res if isinstance(o, Unsortable)).obj assert "Unhandled error!" == str(returned_error) diff --git a/my/core/query_range.py b/my/core/query_range.py index d077225..761b045 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -526,9 +526,8 @@ def test_parse_timedelta_string() -> None: def test_parse_datetime_float() -> None: - pnow = parse_datetime_float("now") - sec_diff = abs((pnow - datetime.now().timestamp())) + sec_diff = abs(pnow - datetime.now().timestamp()) # should probably never fail? could mock time.time # but there seems to be issues with doing that use C-libraries (as time.time) does # https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking diff --git a/my/core/stats.py b/my/core/stats.py index bfedbd2..85c2a99 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -414,7 +414,9 @@ def test_stat_iterable() -> None: dd = datetime.fromtimestamp(123, tz=timezone.utc) day = timedelta(days=3) - X = NamedTuple('X', [('x', int), ('d', datetime)]) + class X(NamedTuple): + x: int + d: datetime def it(): yield RuntimeError('oops!') @@ -452,9 +454,12 @@ def test_guess_datetime() -> None: dd = fromisoformat('2021-02-01T12:34:56Z') - # ugh.. https://github.com/python/mypy/issues/7281 - A = NamedTuple('A', [('x', int)]) - B = NamedTuple('B', [('x', int), ('created', datetime)]) + class A(NamedTuple): + x: int + + class B(NamedTuple): + x: int + created: datetime assert _guess_datetime(A(x=4)) is None assert _guess_datetime(B(x=4, created=dd)) == dd diff --git a/my/core/tests/denylist.py b/my/core/tests/denylist.py index 8016282..2688319 100644 --- a/my/core/tests/denylist.py +++ b/my/core/tests/denylist.py @@ -91,8 +91,7 @@ def test_denylist(tmp_path: Path) -> None: assert "59.40.113.87" not in [i.addr for i in filtered] - with open(tf, "r") as f: - data_json = json.loads(f.read()) + data_json = json.loads(tf.read_text()) assert data_json == [ { diff --git a/my/core/util.py b/my/core/util.py index 0c596fa..fdd10f9 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -12,8 +12,7 @@ from .discovery_pure import HPIModule, _is_not_module_src, has_stats, ignored def modules() -> Iterable[HPIModule]: import my - for m in _iter_all_importables(my): - yield m + yield from _iter_all_importables(my) __NOT_HPI_MODULE__ = 'Import this to mark a python file as a helper, not an actual HPI module' diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 329e330..d74bdc3 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -218,7 +218,7 @@ def _iter_tz_depends_on() -> str: day = str(date.today()) hr = datetime.now().hour hr_truncated = hr // mod * mod - return "{}_{}".format(day, hr_truncated) + return f"{day}_{hr_truncated}" # refresh _iter_tzs every few hours -- don't think a better depends_on is possible dynamically diff --git a/ruff.toml b/ruff.toml index db926da..dda279b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,7 +1,10 @@ +target-version = "py38" # NOTE: inferred from pyproject.toml if present + lint.extend-select = [ "F", # flakes rules -- default, but extend just in case "E", # pycodestyle -- default, but extend just in case "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "UP", # detect deprecated python stdlib stuff ] lint.ignore = [ @@ -28,4 +31,10 @@ lint.ignore = [ "F841", # Local variable `count` is assigned to but never used "F401", # imported but unused ### + +### TODO should be fine to use these with from __future__ import annotations? +### there was some issue with cachew though... double check this? + "UP006", # use type instead of Type + "UP007", # use X | Y instead of Union +### ] From 664c40e3e8a590b63e76354ad907fb6d4567494b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 27 Aug 2024 23:37:17 +0100 Subject: [PATCH 17/55] ruff: enable FBT rules to detect boolean arguments use without kwargs --- my/body/sleep/common.py | 2 +- my/core/__main__.py | 13 +++++++------ my/core/common.py | 9 +++++---- my/core/denylist.py | 5 +++-- my/core/influxdb.py | 2 +- my/core/konsume.py | 2 +- my/core/query.py | 19 +++++++++++++------ my/core/stats.py | 6 +++--- my/core/structure.py | 2 +- my/core/utils/concurrent.py | 2 +- my/endomondo.py | 2 +- my/google/takeout/parser.py | 2 +- my/jawbone/__init__.py | 2 +- my/location/fallback/all.py | 2 +- my/location/fallback/common.py | 2 +- my/tests/tz.py | 2 +- my/time/tz/via_location.py | 4 ++-- my/topcoder.py | 2 +- ruff.toml | 9 +++++---- 19 files changed, 50 insertions(+), 39 deletions(-) diff --git a/my/body/sleep/common.py b/my/body/sleep/common.py index e84c8d5..1100814 100644 --- a/my/body/sleep/common.py +++ b/my/body/sleep/common.py @@ -7,7 +7,7 @@ class Combine: self.modules = modules @cdf - def dataframe(self, with_temperature: bool=True) -> DataFrameT: + def dataframe(self, *, with_temperature: bool=True) -> DataFrameT: import pandas as pd # todo include 'source'? df = pd.concat([m.dataframe() for m in self.modules]) diff --git a/my/core/__main__.py b/my/core/__main__.py index 986b05f..d3c0cc7 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -438,7 +438,7 @@ def _ui_getchar_pick(choices: Sequence[str], prompt: str = 'Select from: ') -> i return result_map[ch] -def _locate_functions_or_prompt(qualified_names: List[str], prompt: bool = True) -> Iterable[Callable[..., Any]]: +def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = True) -> Iterable[Callable[..., Any]]: from .query import QueryException, locate_qualified_function from .stats import is_data_provider @@ -588,7 +588,7 @@ def query_hpi_functions( @click.group() @click.option("--debug", is_flag=True, default=False, help="Show debug logs") -def main(debug: bool) -> None: +def main(*, debug: bool) -> None: ''' Human Programming Interface @@ -637,7 +637,7 @@ def _module_autocomplete(ctx: click.Context, args: Sequence[str], incomplete: st @click.option('-q', '--quick', is_flag=True, help='Only run partial checks (first 100 items)') @click.option('-S', '--skip-config-check', 'skip_conf', is_flag=True, help='Skip configuration check') @click.argument('MODULE', nargs=-1, required=False, shell_complete=_module_autocomplete) -def doctor_cmd(verbose: bool, list_all: bool, quick: bool, skip_conf: bool, module: Sequence[str]) -> None: +def doctor_cmd(*, verbose: bool, list_all: bool, quick: bool, skip_conf: bool, module: Sequence[str]) -> None: ''' Run various checks @@ -671,7 +671,7 @@ def config_create_cmd() -> None: @main.command(name='modules', short_help='list available modules') @click.option('--all', 'list_all', is_flag=True, help='List all modules, including disabled') -def module_cmd(list_all: bool) -> None: +def module_cmd(*, list_all: bool) -> None: '''List available modules''' list_modules(list_all=list_all) @@ -684,7 +684,7 @@ def module_grp() -> None: @module_grp.command(name='requires', short_help='print module reqs') @click.argument('MODULES', shell_complete=_module_autocomplete, nargs=-1, required=True) -def module_requires_cmd(modules: Sequence[str]) -> None: +def module_requires_cmd(*, modules: Sequence[str]) -> None: ''' Print MODULES requirements @@ -701,7 +701,7 @@ def module_requires_cmd(modules: Sequence[str]) -> None: is_flag=True, help='Bypass PEP 668 and install dependencies into the system-wide python package directory.') @click.argument('MODULES', shell_complete=_module_autocomplete, nargs=-1, required=True) -def module_install_cmd(user: bool, parallel: bool, break_system_packages: bool, modules: Sequence[str]) -> None: +def module_install_cmd(*, user: bool, parallel: bool, break_system_packages: bool, modules: Sequence[str]) -> None: ''' Install dependencies for modules using pip @@ -782,6 +782,7 @@ def module_install_cmd(user: bool, parallel: bool, break_system_packages: bool, help='ignore any errors returned as objects from the functions') @click.argument('FUNCTION_NAME', nargs=-1, required=True, shell_complete=_module_autocomplete) def query_cmd( + *, function_name: Sequence[str], output: str, stream: bool, diff --git a/my/core/common.py b/my/core/common.py index ba4ce6b..b97866f 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -26,10 +26,11 @@ Paths = Union[Sequence[PathIsh], PathIsh] DEFAULT_GLOB = '*' def get_files( - pp: Paths, - glob: str=DEFAULT_GLOB, - sort: bool=True, - guess_compression: bool=True, + pp: Paths, + glob: str=DEFAULT_GLOB, + *, + sort: bool=True, + guess_compression: bool=True, ) -> Tuple[Path, ...]: """ Helper function to avoid boilerplate. diff --git a/my/core/denylist.py b/my/core/denylist.py index 7ca0ddf..92faf2c 100644 --- a/my/core/denylist.py +++ b/my/core/denylist.py @@ -96,6 +96,7 @@ class DenyList: def filter( self, itr: Iterator[T], + *, invert: bool = False, ) -> Iterator[T]: denyf = functools.partial(self._allow, deny_map=self.load()) @@ -103,7 +104,7 @@ class DenyList: return filter(lambda x: not denyf(x), itr) return filter(denyf, itr) - def deny(self, key: str, value: Any, write: bool = False) -> None: + def deny(self, key: str, value: Any, *, write: bool = False) -> None: ''' add a key/value pair to the denylist ''' @@ -111,7 +112,7 @@ class DenyList: self._load() self._deny_raw({key: self._stringify_value(value)}, write=write) - def _deny_raw(self, data: Dict[str, Any], write: bool = False) -> None: + def _deny_raw(self, data: Dict[str, Any], *, write: bool = False) -> None: self._deny_raw_list.append(data) if write: self.write() diff --git a/my/core/influxdb.py b/my/core/influxdb.py index b1d6b9b..25eeba1 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -135,7 +135,7 @@ def main() -> None: @main.command(name='populate', short_help='populate influxdb') @click.option('--reset', is_flag=True, help='Reset Influx measurements before inserting', show_default=True) @click.argument('FUNCTION_NAME', type=str, required=True) -def populate(function_name: str, reset: bool) -> None: +def populate(*, function_name: str, reset: bool) -> None: from .__main__ import _locate_functions_or_prompt [provider] = list(_locate_functions_or_prompt([function_name])) # todo could have a non-interactive version which populates from all data sources for the provider? diff --git a/my/core/konsume.py b/my/core/konsume.py index ac1b100..0e4a2fe 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -131,7 +131,7 @@ class UnconsumedError(Exception): # TODO think about error policy later... @contextmanager -def wrap(j, throw=True) -> Iterator[Zoomable]: +def wrap(j, *, throw=True) -> Iterator[Zoomable]: w, children = _wrap(j) yield w diff --git a/my/core/query.py b/my/core/query.py index bc7e222..daf702d 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -131,11 +131,12 @@ def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optiona def _generate_order_by_func( - obj_res: Res[T], - key: Optional[str] = None, - where_function: Optional[Where] = None, - default: Optional[U] = None, - force_unsortable: bool = False, + obj_res: Res[T], + *, + key: Optional[str] = None, + where_function: Optional[Where] = None, + default: Optional[U] = None, + force_unsortable: bool = False, ) -> Optional[OrderFunc]: """ Accepts an object Res[T] (Instance of some class or Exception) @@ -274,6 +275,7 @@ def _wrap_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> Tuple[Iterator[Un # the second being items for which orderfunc returned a non-none value def _handle_unsorted( itr: Iterator[ET], + *, orderfunc: OrderFunc, drop_unsorted: bool, wrap_unsorted: bool @@ -503,7 +505,12 @@ Will attempt to call iter() on the value""") # note: can't just attach sort unsortable values in the same iterable as the # other items because they don't have any lookups for order_key or functions # to handle items in the order_by_lookup dictionary - unsortable, itr = _handle_unsorted(itr, order_by_chosen, drop_unsorted, wrap_unsorted) + unsortable, itr = _handle_unsorted( + itr, + orderfunc=order_by_chosen, + drop_unsorted=drop_unsorted, + wrap_unsorted=wrap_unsorted, + ) # run the sort, with the computed order by function itr = iter(sorted(itr, key=order_by_chosen, reverse=reverse)) # type: ignore[arg-type] diff --git a/my/core/stats.py b/my/core/stats.py index 85c2a99..4c9fb0c 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -30,7 +30,7 @@ Stats = Dict[str, Any] class StatsFun(Protocol): - def __call__(self, quick: bool = False) -> Stats: ... + def __call__(self, *, quick: bool = False) -> Stats: ... # global state that turns on/off quick stats @@ -176,7 +176,7 @@ def guess_stats(module: ModuleType) -> Optional[StatsFun]: if len(providers) == 0: return None - def auto_stats(quick: bool = False) -> Stats: + def auto_stats(*, quick: bool = False) -> Stats: res = {} for k, v in providers.items(): res.update(stat(v, quick=quick, name=k)) @@ -355,7 +355,7 @@ def _stat_item(item): return _guess_datetime(item) -def _stat_iterable(it: Iterable[Any], quick: bool = False) -> Stats: +def _stat_iterable(it: Iterable[Any], *, quick: bool = False) -> Stats: from more_itertools import first, ilen, take # todo not sure if there is something in more_itertools to compute this? diff --git a/my/core/structure.py b/my/core/structure.py index df25e37..149a22a 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -12,7 +12,7 @@ from .logging import make_logger logger = make_logger(__name__, level="info") -def _structure_exists(base_dir: Path, paths: Sequence[str], partial: bool = False) -> bool: +def _structure_exists(base_dir: Path, paths: Sequence[str], *, partial: bool = False) -> bool: """ Helper function for match_structure to check if all subpaths exist at some base directory diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 3553cd9..5f11ab0 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -47,5 +47,5 @@ class DummyExecutor(Executor): return f - def shutdown(self, wait: bool = True, **kwargs) -> None: + def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002 self._shutdown = True diff --git a/my/endomondo.py b/my/endomondo.py index d314e97..1d7acc2 100644 --- a/my/endomondo.py +++ b/my/endomondo.py @@ -44,7 +44,7 @@ def workouts() -> Iterable[Res[Workout]]: from .core.pandas import check_dataframe, DataFrameT @check_dataframe -def dataframe(defensive: bool=True) -> DataFrameT: +def dataframe(*, defensive: bool=True) -> DataFrameT: def it(): for w in workouts(): if isinstance(w, Exception): diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index c4e5682..258ab96 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -91,7 +91,7 @@ def _cachew_depends_on() -> List[str]: # ResultsType is a Union of all of the models in google_takeout_parser @mcachew(depends_on=_cachew_depends_on, logger=logger, force_file=True) -def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: +def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: # noqa: FBT001 error_policy = config.error_policy count = 0 emitted = GoogleEventSet() diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 5d43296..1706a54 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -174,7 +174,7 @@ def hhmm(time: datetime): # return fromstart / tick -def plot_one(sleep: SleepEntry, fig, axes, xlims=None, showtext=True): +def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True): import matplotlib.dates as mdates # type: ignore[import-not-found] span = sleep.completed - sleep.created diff --git a/my/location/fallback/all.py b/my/location/fallback/all.py index 0c7b8cd..a5daa05 100644 --- a/my/location/fallback/all.py +++ b/my/location/fallback/all.py @@ -24,7 +24,7 @@ def fallback_estimators() -> Iterator[LocationEstimator]: yield _home_estimate -def estimate_location(dt: DateExact, first_match: bool=False, under_accuracy: Optional[int] = None) -> FallbackLocation: +def estimate_location(dt: DateExact, *, first_match: bool=False, under_accuracy: Optional[int] = None) -> FallbackLocation: loc = estimate_from(dt, estimators=list(fallback_estimators()), first_match=first_match, under_accuracy=under_accuracy) # should never happen if the user has home configured if loc is None: diff --git a/my/location/fallback/common.py b/my/location/fallback/common.py index fd508c6..13bc603 100644 --- a/my/location/fallback/common.py +++ b/my/location/fallback/common.py @@ -18,7 +18,7 @@ class FallbackLocation(LocationProtocol): elevation: Optional[float] = None datasource: Optional[str] = None # which module provided this, useful for debugging - def to_location(self, end: bool = False) -> Location: + def to_location(self, *, end: bool = False) -> Location: ''' by default the start date is used for the location If end is True, the start date + duration is used diff --git a/my/tests/tz.py b/my/tests/tz.py index db88278..92d8f3b 100644 --- a/my/tests/tz.py +++ b/my/tests/tz.py @@ -18,7 +18,7 @@ def getzone(dt: datetime) -> str: @pytest.mark.parametrize('fast', [False, True]) -def test_iter_tzs(fast: bool, config) -> None: +def test_iter_tzs(*, fast: bool, config) -> None: # TODO hmm.. maybe need to make sure we start with empty config? config.time.tz.via_location.fast = fast diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index d74bdc3..156a5db 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -94,7 +94,7 @@ logger = make_logger(__name__) @lru_cache(None) -def _timezone_finder(fast: bool) -> Any: +def _timezone_finder(*, fast: bool) -> Any: if fast: # less precise, but faster from timezonefinder import TimezoneFinderL as Finder @@ -304,7 +304,7 @@ def localize(dt: datetime) -> datetime_aware: return tz.localize(dt) -def stats(quick: bool = False) -> Stats: +def stats(*, quick: bool = False) -> Stats: if quick: prev, config.sort_locations = config.sort_locations, False res = {'first': next(_iter_local_dates())} diff --git a/my/topcoder.py b/my/topcoder.py index 8e39252..07f71be 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -58,7 +58,7 @@ def _parse_one(p: Path) -> Iterator[Res[Competition]]: h.pop_if_primitive('version', 'id') h = h.zoom('result') - h.check('success', True) + h.check('success', expected=True) h.check('status', 200) h.pop_if_primitive('metadata') diff --git a/ruff.toml b/ruff.toml index dda279b..a8af399 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,10 +1,11 @@ target-version = "py38" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ - "F", # flakes rules -- default, but extend just in case - "E", # pycodestyle -- default, but extend just in case - "C4", # flake8-comprehensions -- unnecessary list/map/dict calls - "UP", # detect deprecated python stdlib stuff + "F", # flakes rules -- default, but extend just in case + "E", # pycodestyle -- default, but extend just in case + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "UP", # detect deprecated python stdlib stuff + "FBT", # detect use of boolean arguments ] lint.ignore = [ From b594377a599acbc14eb9a2b17e88ca87fcc1a727 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 00:00:54 +0100 Subject: [PATCH 18/55] ruff: enable RUF ruleset --- my/arbtt.py | 2 +- my/bluemaestro.py | 4 ++-- my/core/__main__.py | 2 +- my/core/error.py | 4 ++-- my/core/source.py | 2 +- my/core/structure.py | 22 +++++++++++----------- my/core/time.py | 2 +- my/core/util.py | 2 +- my/experimental/destructive_parsing.py | 2 +- my/google/takeout/html.py | 2 +- my/location/common.py | 2 +- my/photos/main.py | 2 +- my/polar.py | 2 +- my/twitter/android.py | 5 +++-- ruff.toml | 3 +++ 15 files changed, 31 insertions(+), 27 deletions(-) diff --git a/my/arbtt.py b/my/arbtt.py index 6de8cb2..2bcf291 100644 --- a/my/arbtt.py +++ b/my/arbtt.py @@ -81,7 +81,7 @@ def entries() -> Iterable[Entry]: cmds = [base] # rely on default else: # otherwise, 'merge' them - cmds = [base + ['--logfile', f] for f in inps] + cmds = [[*base, '--logfile', f] for f in inps] import ijson.backends.yajl2_cffi as ijson # type: ignore from subprocess import Popen, PIPE diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 12c114f..50338bb 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -104,7 +104,7 @@ def measurements() -> Iterable[Res[Measurement]]: f'SELECT "{path.name}" as name, Time, Temperature, Humidity, Pressure, Dewpoint FROM data ORDER BY log_index' ) oldfmt = True - db_dts = list(db.execute('SELECT last_download FROM info'))[0][0] + [(db_dts,)] = db.execute('SELECT last_download FROM info') if db_dts == 'N/A': # ??? happens for 20180923-20180928 continue @@ -137,7 +137,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] + 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. diff --git a/my/core/__main__.py b/my/core/__main__.py index d3c0cc7..3af8e08 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -392,7 +392,7 @@ def module_install(*, user: bool, module: Sequence[str], parallel: bool=False, b # I think it only helps for pypi artifacts (not git!), # and only if they weren't cached for r in requirements: - cmds.append(pre_cmd + [r]) + cmds.append([*pre_cmd, r]) else: if parallel: warning('parallel install is not supported on this platform, installing sequentially...') diff --git a/my/core/error.py b/my/core/error.py index 7489f69..cd8d093 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -153,7 +153,7 @@ def test_sort_res_by() -> None: Exc('last'), ] - results2 = sort_res_by(ress + [0], lambda x: int(x)) + results2 = sort_res_by([*ress, 0], lambda x: int(x)) assert results2 == [Exc('last'), 0] + results[:-1] assert sort_res_by(['caba', 'a', 'aba', 'daba'], key=lambda x: len(x)) == ['a', 'aba', 'caba', 'daba'] @@ -166,7 +166,7 @@ def test_sort_res_by() -> None: def set_error_datetime(e: Exception, dt: Optional[datetime]) -> None: if dt is None: return - e.args = e.args + (dt,) + e.args = (*e.args, dt) # todo not sure if should return new exception? diff --git a/my/core/source.py b/my/core/source.py index 6e0a78a..4510ef0 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -61,7 +61,7 @@ def import_source( warnings.warn(f"""If you don't want to use this module, to hide this message, add '{module_name}' to your core config disabled_modules in your config, like: class core: - disabled_modules = [{repr(module_name)}] + disabled_modules = [{module_name!r}] """) # try to check if this is a config error or based on dependencies not being installed if isinstance(err, (ImportError, AttributeError)): diff --git a/my/core/structure.py b/my/core/structure.py index 149a22a..be5b307 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -67,21 +67,21 @@ def match_structure( export_dir ├── exp_2020 - │   ├── channel_data - │   │   ├── data1 - │   │   └── data2 - │   ├── index.json - │   ├── messages - │   │   └── messages.csv - │   └── profile - │   └── settings.json + │ ├── channel_data + │ │ ├── data1 + │ │ └── data2 + │ ├── index.json + │ ├── messages + │ │ └── messages.csv + │ └── profile + │ └── settings.json └── exp_2021 ├── channel_data - │   ├── data1 - │   └── data2 + │ ├── data1 + │ └── data2 ├── index.json ├── messages - │   └── messages.csv + │ └── messages.csv └── profile └── settings.json diff --git a/my/core/time.py b/my/core/time.py index 83a407b..5a47c3d 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -21,7 +21,7 @@ def user_forced() -> Sequence[str]: def _abbr_to_timezone_map() -> Dict[str, pytz.BaseTzInfo]: # also force UTC to always correspond to utc # this makes more sense than Zulu it ends up by default - timezones = pytz.all_timezones + ['UTC'] + list(user_forced()) + timezones = [*pytz.all_timezones, 'UTC', *user_forced()] res: Dict[str, pytz.BaseTzInfo] = {} for tzname in timezones: diff --git a/my/core/util.py b/my/core/util.py index fdd10f9..b49acf6 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -74,7 +74,7 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu continue rel_pt = pkg_dir_path.relative_to(pkg_pth) - pkg_pref = '.'.join((pkg_name, ) + rel_pt.parts) + pkg_pref = '.'.join((pkg_name, *rel_pt.parts)) yield from _walk_packages( (str(pkg_dir_path), ), prefix=f'{pkg_pref}.', diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py index 05c5920..056cc0b 100644 --- a/my/experimental/destructive_parsing.py +++ b/my/experimental/destructive_parsing.py @@ -26,7 +26,7 @@ class Helper: assert actual == expected, (key, actual, expected) def zoom(self, key: str) -> 'Helper': - return self.manager.helper(item=self.item.pop(key), path=self.path + (key,)) + return self.manager.helper(item=self.item.pop(key), path=(*self.path, key)) def is_empty(x) -> bool: diff --git a/my/google/takeout/html.py b/my/google/takeout/html.py index 3ce692c..750beac 100644 --- a/my/google/takeout/html.py +++ b/my/google/takeout/html.py @@ -122,7 +122,7 @@ class TakeoutHTMLParser(HTMLParser): # JamiexxVEVO # Jun 21, 2018, 5:48:34 AM # Products: - #  YouTube + # YouTube def handle_data(self, data): if self.state == State.OUTSIDE: if data[:-1].strip() in ("Watched", "Visited"): diff --git a/my/location/common.py b/my/location/common.py index 510e005..f406370 100644 --- a/my/location/common.py +++ b/my/location/common.py @@ -70,7 +70,7 @@ def locations_to_gpx(locations: Iterable[LocationProtocol], buffer: TextIO) -> I ) except AttributeError: yield TypeError( - f"Expected a Location or Location-like object, got {type(location)} {repr(location)}" + f"Expected a Location or Location-like object, got {type(location)} {location!r}" ) continue gpx_segment.points.append(point) diff --git a/my/photos/main.py b/my/photos/main.py index 6262eac..63a6fea 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -209,7 +209,7 @@ def print_all() -> None: if isinstance(p, Exception): print('ERROR!', p) else: - print(f"{str(p.dt):25} {p.path} {p.geo}") + print(f"{p.dt!s:25} {p.path} {p.geo}") # todo cachew -- improve AttributeError: type object 'tuple' has no attribute '__annotations__' -- improve errors? # todo cachew -- invalidate if function code changed? diff --git a/my/polar.py b/my/polar.py index cd2c719..197de18 100644 --- a/my/polar.py +++ b/my/polar.py @@ -27,7 +27,7 @@ class polar(user_config): ''' Polar config is optional, you only need it if you want to specify custom 'polar_dir' ''' - polar_dir: PathIsh = Path('~/.polar').expanduser() + polar_dir: PathIsh = Path('~/.polar').expanduser() # noqa: RUF009 defensive: bool = True # pass False if you want it to fail faster on errors (useful for debugging) diff --git a/my/twitter/android.py b/my/twitter/android.py index f40ad0e..7adfeb6 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -155,7 +155,7 @@ _SELECT_OWN_TWEETS = '_SELECT_OWN_TWEETS' def get_own_user_id(conn) -> str: # unclear what's the reliable way to query it, so we use multiple different ones and arbitrate # NOTE: 'SELECT DISTINCT ev_owner_id FROM lists' doesn't work, might include lists from other people? - res = set() + res: Set[str] = set() for q in [ 'SELECT DISTINCT list_mapping_user_id FROM list_mapping', 'SELECT DISTINCT owner_id FROM cursors', @@ -164,7 +164,8 @@ def get_own_user_id(conn) -> str: for (r,) in conn.execute(q): res.add(r) assert len(res) == 1, res - return str(list(res)[0]) + [r] = res + return r # NOTE: diff --git a/ruff.toml b/ruff.toml index a8af399..2b77622 100644 --- a/ruff.toml +++ b/ruff.toml @@ -6,6 +6,7 @@ lint.extend-select = [ "C4", # flake8-comprehensions -- unnecessary list/map/dict calls "UP", # detect deprecated python stdlib stuff "FBT", # detect use of boolean arguments + "RUF", # various ruff-specific rules ] lint.ignore = [ @@ -38,4 +39,6 @@ lint.ignore = [ "UP006", # use type instead of Type "UP007", # use X | Y instead of Union ### + "RUF100", # unused noqa -- handle later + "RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs ] From d0df8e8f2db2dd0a1776fa7bad54f2bbbba1bde1 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 00:29:06 +0100 Subject: [PATCH 19/55] ruff: enable PLR rules and fix bug in my.github.gdpr._is_bot --- my/github/gdpr.py | 2 +- ruff.toml | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/my/github/gdpr.py b/my/github/gdpr.py index 4ca8e84..acbeb8f 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -145,7 +145,7 @@ def _parse_repository(d: Dict) -> Event: def _is_bot(user: Optional[str]) -> bool: if user is None: return False - return "[bot]" in "user" + return "[bot]" in user def _parse_issue_comment(d: Dict) -> Event: diff --git a/ruff.toml b/ruff.toml index 2b77622..69af75a 100644 --- a/ruff.toml +++ b/ruff.toml @@ -7,6 +7,10 @@ lint.extend-select = [ "UP", # detect deprecated python stdlib stuff "FBT", # detect use of boolean arguments "RUF", # various ruff-specific rules + + "PLR", + # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks + # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] lint.ignore = [ @@ -41,4 +45,16 @@ lint.ignore = [ ### "RUF100", # unused noqa -- handle later "RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs + +### these are just nitpicky, we usually know better + "PLR0911", # too many return statements + "PLR0912", # too many branches + "PLR0913", # too many function arguments + "PLR0915", # too many statements + "PLR1714", # consider merging multiple comparisons + "PLR2044", # line with empty comment + "PLR5501", # use elif instead of else if + "PLR2004", # magic value in comparison -- super annoying in tests +### + "PLR0402", # import X.Y as Y -- TODO maybe consider enabling it, but double check ] From 72cc8ff3acae427232c28ca32080f22c9164f7d7 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 01:13:18 +0100 Subject: [PATCH 20/55] ruff: enable B warnings (mainly suppressed exceptions and unused variables) --- my/bluemaestro.py | 2 +- my/body/exercise/cross_trainer.py | 2 +- my/coding/github.py | 13 ++++++++----- my/core/__main__.py | 4 ++-- my/core/cachew.py | 6 ++++-- my/core/common.py | 7 +++---- my/core/error.py | 2 +- my/core/hpi_compat.py | 4 ++-- my/core/init.py | 6 +++--- my/core/logging.py | 6 +++--- my/core/orgmode.py | 12 ++++++------ my/core/query.py | 4 ++-- my/core/query_range.py | 2 +- my/core/source.py | 2 +- my/core/stats.py | 2 +- my/core/util.py | 4 ++-- my/core/utils/itertools.py | 7 ++++--- my/core/warnings.py | 10 +++++----- my/jawbone/__init__.py | 2 +- my/location/google.py | 11 ++++++----- my/media/imdb.py | 2 +- my/polar.py | 4 ++-- my/reddit/rexport.py | 6 +++--- my/rss/common.py | 2 +- my/tests/location/google.py | 4 ++-- my/tests/shared_tz_config.py | 4 ++-- my/time/tz/common.py | 2 +- my/twitter/archive.py | 4 ++-- ruff.toml | 10 +++++++++- tests/github.py | 4 +++- 30 files changed, 83 insertions(+), 67 deletions(-) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 50338bb..5d0968b 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -153,7 +153,7 @@ def measurements() -> Iterable[Res[Measurement]]: oldfmt = False db_dt = None - for i, (name, tsc, temp, hum, pres, dewp) in enumerate(datas): + for (name, tsc, temp, hum, pres, dewp) in datas: if is_bad_table(name): continue diff --git a/my/body/exercise/cross_trainer.py b/my/body/exercise/cross_trainer.py index d073f43..edbb557 100644 --- a/my/body/exercise/cross_trainer.py +++ b/my/body/exercise/cross_trainer.py @@ -105,7 +105,7 @@ def dataframe() -> DataFrameT: rows = [] idxs = [] # type: ignore[var-annotated] NO_ENDOMONDO = 'no endomondo matches' - for i, row in mdf.iterrows(): + for _i, row in mdf.iterrows(): rd = row.to_dict() mdate = row['date'] if pd.isna(mdate): diff --git a/my/coding/github.py b/my/coding/github.py index 9358b04..de64f05 100644 --- a/my/coding/github.py +++ b/my/coding/github.py @@ -1,9 +1,12 @@ -import warnings +from typing import TYPE_CHECKING -warnings.warn('my.coding.github is deprecated! Please use my.github.all instead!') +from my.core import warnings + +warnings.high('my.coding.github is deprecated! Please use my.github.all instead!') # todo why aren't DeprecationWarning shown by default?? -from ..github.all import events, get_events +if not TYPE_CHECKING: + from ..github.all import events, get_events -# todo deprecate properly -iter_events = events + # todo deprecate properly + iter_events = events diff --git a/my/core/__main__.py b/my/core/__main__.py index 3af8e08..c5e4552 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -456,9 +456,9 @@ def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = Tr # user to select a 'data provider' like function try: mod = importlib.import_module(qualname) - except Exception: + except Exception as ie: eprint(f"During fallback, importing '{qualname}' as module failed") - raise qr_err + raise qr_err from ie # find data providers in this module data_providers = [f for _, f in inspect.getmembers(mod, inspect.isfunction) if is_data_provider(f)] diff --git a/my/core/cachew.py b/my/core/cachew.py index e0e7adf..dc6ed79 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -2,7 +2,6 @@ from .internal import assert_subpackage; assert_subpackage(__name__) import logging import sys -import warnings from contextlib import contextmanager from pathlib import Path from typing import ( @@ -20,6 +19,9 @@ from typing import ( import appdirs # type: ignore[import-untyped] +from . import warnings + + PathIsh = Union[str, Path] # avoid circular import from .common @@ -116,7 +118,7 @@ def _mcachew_impl(cache_path=_cache_path_dflt, **kwargs): try: import cachew except ModuleNotFoundError: - warnings.warn('cachew library not found. You might want to install it to speed things up. See https://github.com/karlicoss/cachew') + warnings.high('cachew library not found. You might want to install it to speed things up. See https://github.com/karlicoss/cachew') return lambda orig_func: orig_func else: kwargs['cache_path'] = cache_path diff --git a/my/core/common.py b/my/core/common.py index b97866f..5f8d03a 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -1,5 +1,4 @@ import os -import warnings from glob import glob as do_glob from pathlib import Path from typing import ( @@ -15,7 +14,7 @@ from typing import ( ) from . import compat -from . import warnings as core_warnings +from . import warnings as warnings # some helper functions # TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit @@ -63,7 +62,7 @@ def get_files( gs = str(src) if '*' in gs: if glob != DEFAULT_GLOB: - warnings.warn(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") + warnings.medium(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") paths.extend(map(Path, do_glob(gs))) elif os.path.isdir(str(src)): # NOTE: we're using os.path here on purpose instead of src.is_dir @@ -85,7 +84,7 @@ def get_files( if len(paths) == 0: # todo make it conditionally defensive based on some global settings - core_warnings.high(f''' + warnings.high(f''' {caller()}: no paths were matched against {pp}. This might result in missing data. Likely, the directory you passed is empty. '''.strip()) # traceback is useful to figure out what config caused it? diff --git a/my/core/error.py b/my/core/error.py index cd8d093..e869614 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -119,7 +119,7 @@ def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T] group = [] results: List[Res[T]] = [] - for v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? + for _v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? results.extend(grp) results.extend(group) # handle last group (it will always be errors only) diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index bad0b17..9330e49 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -6,7 +6,7 @@ import inspect import os import re from types import ModuleType -from typing import Iterator, List, Optional, TypeVar +from typing import Iterator, List, Optional, Sequence, TypeVar from . import warnings @@ -71,7 +71,7 @@ def pre_pip_dal_handler( name: str, e: ModuleNotFoundError, cfg, - requires=[], + requires: Sequence[str] = (), ) -> ModuleType: ''' https://github.com/karlicoss/HPI/issues/79 diff --git a/my/core/init.py b/my/core/init.py index 49148de..7a30955 100644 --- a/my/core/init.py +++ b/my/core/init.py @@ -25,7 +25,7 @@ def setup_config() -> None: warnings.warn(f""" 'my.config' package isn't found! (expected at '{mycfg_dir}'). This is likely to result in issues. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-modules for more info. -""".strip()) +""".strip(), stacklevel=1) return mpath = str(mycfg_dir) @@ -47,7 +47,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-mo warnings.warn(f""" Importing 'my.config' failed! (error: {ex}). This is likely to result in issues. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-modules for more info. -""") +""", stacklevel=1) else: # defensive just in case -- __file__ may not be present if there is some dynamic magic involved used_config_file = getattr(my.config, '__file__', None) @@ -63,7 +63,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-mo Expected my.config to be located at {mycfg_dir}, but instead its path is {used_config_path}. This will likely cause issues down the line -- double check {mycfg_dir} structure. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-modules for more info. -""", +""", stacklevel=1 ) diff --git a/my/core/logging.py b/my/core/logging.py index 734c1e0..bdee9aa 100644 --- a/my/core/logging.py +++ b/my/core/logging.py @@ -15,7 +15,7 @@ def test() -> None: ## prepare exception for later try: - None.whatever # type: ignore[attr-defined] + None.whatever # type: ignore[attr-defined] # noqa: B018 except Exception as e: ex = e ## @@ -146,7 +146,7 @@ def _setup_handlers_and_formatters(name: str) -> None: # try colorlog first, so user gets nice colored logs import colorlog except ModuleNotFoundError: - warnings.warn("You might want to 'pip install colorlog' for nice colored logs") + warnings.warn("You might want to 'pip install colorlog' for nice colored logs", stacklevel=1) formatter = logging.Formatter(FORMAT_NOCOLOR) else: # log_color/reset are specific to colorlog @@ -233,7 +233,7 @@ def get_enlighten(): try: import enlighten # type: ignore[import-untyped] except ModuleNotFoundError: - warnings.warn("You might want to 'pip install enlighten' for a nice progress bar") + warnings.warn("You might want to 'pip install enlighten' for a nice progress bar", stacklevel=1) return Mock() diff --git a/my/core/orgmode.py b/my/core/orgmode.py index d9a254c..c70ded6 100644 --- a/my/core/orgmode.py +++ b/my/core/orgmode.py @@ -6,12 +6,12 @@ from datetime import datetime def parse_org_datetime(s: str) -> datetime: s = s.strip('[]') - for fmt, cl in [ - ("%Y-%m-%d %a %H:%M", datetime), - ("%Y-%m-%d %H:%M" , datetime), - # todo not sure about these... fallback on 00:00? - # ("%Y-%m-%d %a" , date), - # ("%Y-%m-%d" , date), + for fmt, _cls in [ + ("%Y-%m-%d %a %H:%M", datetime), + ("%Y-%m-%d %H:%M" , datetime), + # todo not sure about these... fallback on 00:00? + # ("%Y-%m-%d %a" , date), + # ("%Y-%m-%d" , date), ]: try: return datetime.strptime(s, fmt) diff --git a/my/core/query.py b/my/core/query.py index daf702d..c337e5c 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -72,7 +72,7 @@ def locate_function(module_name: str, function_name: str) -> Callable[[], Iterab if func is not None and callable(func): return func except Exception as e: - raise QueryException(str(e)) + raise QueryException(str(e)) # noqa: B904 raise QueryException(f"Could not find function '{function_name}' in '{module_name}'") @@ -468,7 +468,7 @@ Will attempt to call iter() on the value""") try: itr: Iterator[ET] = iter(it) except TypeError as t: - raise QueryException("Could not convert input src to an Iterator: " + str(t)) + raise QueryException("Could not convert input src to an Iterator: " + str(t)) # noqa: B904 # if both drop_exceptions and drop_exceptions are provided for some reason, # should raise exceptions before dropping them diff --git a/my/core/query_range.py b/my/core/query_range.py index 761b045..0a1b321 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -109,7 +109,7 @@ def _datelike_to_float(dl: Any) -> float: try: return parse_datetime_float(dl) except QueryException as q: - raise QueryException(f"While attempting to extract datetime from {dl}, to order by datetime:\n\n" + str(q)) + raise QueryException(f"While attempting to extract datetime from {dl}, to order by datetime:\n\n" + str(q)) # noqa: B904 class RangeTuple(NamedTuple): diff --git a/my/core/source.py b/my/core/source.py index 4510ef0..52c58c1 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -62,7 +62,7 @@ def import_source( class core: disabled_modules = [{module_name!r}] -""") +""", stacklevel=1) # try to check if this is a config error or based on dependencies not being installed if isinstance(err, (ImportError, AttributeError)): matched_config_err = warn_my_config_import_error(err, module_name=module_name, help_url=help_url) diff --git a/my/core/stats.py b/my/core/stats.py index 4c9fb0c..aa05355 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -440,7 +440,7 @@ def _guess_datetime(x: Any) -> Optional[datetime]: d = asdict(x) except: # noqa: E722 bare except return None - for k, v in d.items(): + for _k, v in d.items(): if isinstance(v, datetime): return v return None diff --git a/my/core/util.py b/my/core/util.py index b49acf6..fb3edf8 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -93,11 +93,11 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterable[HPIModule]: """ Modified version of https://github.com/python/cpython/blob/d50a0700265536a20bcce3fb108c954746d97625/Lib/pkgutil.py#L53, - to alvoid importing modules that are skipped + to avoid importing modules that are skipped """ from .core_config import config - def seen(p, m={}): + def seen(p, m={}): # noqa: B006 if p in m: return True m[p] = True diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 66f82bd..b945ad8 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -24,6 +24,8 @@ import more_itertools from decorator import decorator from ..compat import ParamSpec +from .. import warnings as core_warnings + T = TypeVar('T') K = TypeVar('K') @@ -142,8 +144,7 @@ def _warn_if_empty(func, *args, **kwargs): if isinstance(iterable, Sized): sz = len(iterable) if sz == 0: - # todo use hpi warnings here? - warnings.warn(f"Function {func} returned empty container, make sure your config paths are correct") + core_warnings.medium(f"Function {func} returned empty container, make sure your config paths are correct") return iterable else: # must be an iterator @@ -153,7 +154,7 @@ def _warn_if_empty(func, *args, **kwargs): yield i empty = False if empty: - warnings.warn(f"Function {func} didn't emit any data, make sure your config paths are correct") + core_warnings.medium(f"Function {func} didn't emit any data, make sure your config paths are correct") return wit() diff --git a/my/core/warnings.py b/my/core/warnings.py index 82e539b..2ffc3e4 100644 --- a/my/core/warnings.py +++ b/my/core/warnings.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Optional import click -def _colorize(x: str, color: Optional[str]=None) -> str: +def _colorize(x: str, color: Optional[str] = None) -> str: if color is None: return x @@ -24,10 +24,10 @@ def _colorize(x: str, color: Optional[str]=None) -> str: return click.style(x, fg=color) -def _warn(message: str, *args, color: Optional[str]=None, **kwargs) -> None: +def _warn(message: str, *args, color: Optional[str] = None, **kwargs) -> None: stacklevel = kwargs.get('stacklevel', 1) - kwargs['stacklevel'] = stacklevel + 2 # +1 for this function, +1 for medium/high wrapper - warnings.warn(_colorize(message, color=color), *args, **kwargs) + kwargs['stacklevel'] = stacklevel + 2 # +1 for this function, +1 for medium/high wrapper + warnings.warn(_colorize(message, color=color), *args, **kwargs) # noqa: B028 def low(message: str, *args, **kwargs) -> None: @@ -55,4 +55,4 @@ if not TYPE_CHECKING: def warn(*args, **kwargs): import warnings - return warnings.warn(*args, **kwargs) + return warnings.warn(*args, **kwargs) # noqa: B028 diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 1706a54..affe230 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -274,7 +274,7 @@ def plot() -> None: fig: Figure = plt.figure(figsize=(15, sleeps_count * 1)) axarr = fig.subplots(nrows=len(sleeps)) - for i, (sleep, axes) in enumerate(zip(sleeps, axarr)): + for (sleep, axes) in zip(sleeps, axarr): plot_one(sleep, fig, axes, showtext=True) used = melatonin_data.get(sleep.date_, None) sused: str diff --git a/my/location/google.py b/my/location/google.py index a7a92d3..b966ec6 100644 --- a/my/location/google.py +++ b/my/location/google.py @@ -22,9 +22,10 @@ import geopy # type: ignore from my.core import stat, Stats, make_logger from my.core.cachew import cache_dir, mcachew -from my.core.warnings import high +from my.core import warnings -high("Please set up my.google.takeout.parser module for better takeout support") + +warnings.high("Please set up my.google.takeout.parser module for better takeout support") # otherwise uses ijson @@ -52,8 +53,7 @@ def _iter_via_ijson(fo) -> Iterable[TsLatLon]: # pip3 install ijson cffi import ijson.backends.yajl2_cffi as ijson # type: ignore except: - import warnings - warnings.warn("Falling back to default ijson because 'cffi' backend isn't found. It's up to 2x faster, you might want to check it out") + warnings.medium("Falling back to default ijson because 'cffi' backend isn't found. It's up to 2x faster, you might want to check it out") import ijson # type: ignore for d in ijson.items(fo, 'locations.item'): @@ -105,7 +105,8 @@ def _iter_locations_fo(fit) -> Iterable[Location]: errors += 1 if float(errors) / total > 0.01: # todo make defensive? - raise RuntimeError('too many errors! aborting') + # todo exceptiongroup? + raise RuntimeError('too many errors! aborting') # noqa: B904 else: continue diff --git a/my/media/imdb.py b/my/media/imdb.py index df6d62d..c66f5dc 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -22,7 +22,7 @@ def iter_movies() -> Iterator[Movie]: with last.open() as fo: reader = csv.DictReader(fo) - for i, line in enumerate(reader): + for line in reader: # TODO extract directors?? title = line['Title'] rating = int(line['You rated']) diff --git a/my/polar.py b/my/polar.py index 197de18..9125f17 100644 --- a/my/polar.py +++ b/my/polar.py @@ -166,7 +166,7 @@ class Loader: htags: List[str] = [] if 'tags' in h: ht = h['tags'].zoom() - for k, v in list(ht.items()): + for _k, v in list(ht.items()): ctag = v.zoom() ctag['id'].consume() ct = ctag['label'].zoom() @@ -199,7 +199,7 @@ class Loader: def load_items(self, metas: Json) -> Iterable[Highlight]: - for p, meta in metas.items(): + for _p, meta in metas.items(): with wrap(meta, throw=not config.defensive) as meta: yield from self.load_item(meta) diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py index 6a6be61..5dcd7d9 100644 --- a/my/reddit/rexport.py +++ b/my/reddit/rexport.py @@ -144,9 +144,9 @@ if not TYPE_CHECKING: try: # here we just check that types are available, we don't actually want to import them # fmt: off - dal.Subreddit - dal.Profile - dal.Multireddit + dal.Subreddit # noqa: B018 + dal.Profil # noqa: B018e + dal.Multireddit # noqa: B018 # fmt: on except AttributeError as ae: warnings.high(f'{ae} : please update "rexport" installation') diff --git a/my/rss/common.py b/my/rss/common.py index 54067d6..bb75297 100644 --- a/my/rss/common.py +++ b/my/rss/common.py @@ -32,7 +32,7 @@ def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscri by_url: Dict[str, Subscription] = {} # ah. dates are used for sorting - for when, state in sorted(states): + for _when, state in sorted(states): # TODO use 'when'? for feed in state: if feed.url not in by_url: diff --git a/my/tests/location/google.py b/my/tests/location/google.py index 612522b..43b8646 100644 --- a/my/tests/location/google.py +++ b/my/tests/location/google.py @@ -44,8 +44,8 @@ def _prepare_takeouts_dir(tmp_path: Path) -> Path: try: track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) - except ValueError: - raise RuntimeError('testdata not found, setup git submodules?') + except ValueError as e: + raise RuntimeError('testdata not found, setup git submodules?') from e # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs import zipfile diff --git a/my/tests/shared_tz_config.py b/my/tests/shared_tz_config.py index 3d95a9e..810d989 100644 --- a/my/tests/shared_tz_config.py +++ b/my/tests/shared_tz_config.py @@ -49,8 +49,8 @@ def _prepare_takeouts_dir(tmp_path: Path) -> Path: try: track = one(testdata().rglob('italy-slovenia-2017-07-29.json')) - except ValueError: - raise RuntimeError('testdata not found, setup git submodules?') + except ValueError as e: + raise RuntimeError('testdata not found, setup git submodules?') from e # todo ugh. unnecessary zipping, but at the moment takeout provider doesn't support plain dirs import zipfile diff --git a/my/time/tz/common.py b/my/time/tz/common.py index 89150c7..13c8ac0 100644 --- a/my/time/tz/common.py +++ b/my/time/tz/common.py @@ -33,7 +33,7 @@ def default_policy() -> TzPolicy: def localize_with_policy( lfun: Callable[[datetime], datetime_aware], dt: datetime, - policy: TzPolicy=default_policy() + policy: TzPolicy=default_policy() # noqa: B008 ) -> datetime_aware: tz = dt.tzinfo if tz is None: diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 685f7fc..d326d70 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -14,9 +14,9 @@ except ImportError as ie: try: from my.config import twitter as user_config # type: ignore[assignment] except ImportError: - raise ie # raise the original exception.. must be something else + raise ie # raise the original exception.. must be something else # noqa: B904 else: - from ..core import warnings + from my.core import warnings warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') ## diff --git a/ruff.toml b/ruff.toml index 69af75a..3d97fc9 100644 --- a/ruff.toml +++ b/ruff.toml @@ -7,8 +7,11 @@ lint.extend-select = [ "UP", # detect deprecated python stdlib stuff "FBT", # detect use of boolean arguments "RUF", # various ruff-specific rules + "PLR", # 'refactor' rules + "B", # 'bugbear' set -- various possible bugs + + - "PLR", # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] @@ -57,4 +60,9 @@ lint.ignore = [ "PLR2004", # magic value in comparison -- super annoying in tests ### "PLR0402", # import X.Y as Y -- TODO maybe consider enabling it, but double check + + "B009", # calling gettattr with constant attribute -- this is useful to convince mypy + "B010", # same as above, but setattr + "B017", # pytest.raises(Exception) + "B023", # seems to result in false positives? ] diff --git a/tests/github.py b/tests/github.py index 6b7df23..ed89053 100644 --- a/tests/github.py +++ b/tests/github.py @@ -5,11 +5,13 @@ from more_itertools import ilen def test_gdpr() -> None: import my.github.gdpr as gdpr + assert ilen(gdpr.events()) > 100 def test() -> None: - from my.coding.github import get_events + from my.github.all import get_events + events = get_events() assert ilen(events) > 100 for e in events: From 985c0f94e633dcab9f51e0da459ad049d8f8c73b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 01:51:14 +0100 Subject: [PATCH 21/55] ruff: attempt to enable ARG checks, suppress in some places --- my/core/pytest.py | 2 +- my/core/utils/itertools.py | 6 +++--- my/pdfs.py | 2 +- ruff.toml | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/my/core/pytest.py b/my/core/pytest.py index c73c71a..e514957 100644 --- a/my/core/pytest.py +++ b/my/core/pytest.py @@ -15,7 +15,7 @@ if typing.TYPE_CHECKING or under_pytest: parametrize = pytest.mark.parametrize else: - def parametrize(*args, **kwargs): + def parametrize(*_args, **_kwargs): def wrapper(f): return f diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index b945ad8..ae9402d 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -63,7 +63,7 @@ def test_ensure_unique() -> None: list(it) # hacky way to force distinct objects? - list(ensure_unique(dups, key=lambda i: object())) + list(ensure_unique(dups, key=lambda _: object())) def make_dict( @@ -115,7 +115,7 @@ def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.k # so seems easiest to just use specialize instantiations of decorator instead if TYPE_CHECKING: - def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, List[LV]]: ... + def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, List[LV]]: ... # noqa: ARG001 else: listify = _listify @@ -162,7 +162,7 @@ def _warn_if_empty(func, *args, **kwargs): if TYPE_CHECKING: FF = TypeVar('FF', bound=Callable[..., Iterable]) - def warn_if_empty(f: FF) -> FF: ... + def warn_if_empty(func: FF) -> FF: ... # noqa: ARG001 else: warn_if_empty = _warn_if_empty diff --git a/my/pdfs.py b/my/pdfs.py index db49c0e..de9324d 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -25,7 +25,7 @@ class config(Protocol): def paths(self) -> Paths: return () # allowed to be empty for 'filelist' logic - def is_ignored(self, p: Path) -> bool: + def is_ignored(self, p: Path) -> bool: # noqa: ARG002 """ You can override this in user config if you want to ignore some files that are tooheavy """ diff --git a/ruff.toml b/ruff.toml index 3d97fc9..e7c6f07 100644 --- a/ruff.toml +++ b/ruff.toml @@ -10,8 +10,8 @@ lint.extend-select = [ "PLR", # 'refactor' rules "B", # 'bugbear' set -- various possible bugs - - + # "FA", # TODO enable later after we make sure cachew works? + # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] From bd1e5d2f1167232017fcf5aad34c554582bedc69 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 02:16:12 +0100 Subject: [PATCH 22/55] ruff: enable PERF checks set --- my/core/query.py | 2 +- my/core/stats.py | 2 +- my/polar.py | 2 +- ruff.toml | 9 +++++++++ 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/my/core/query.py b/my/core/query.py index c337e5c..45806fb 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -114,7 +114,7 @@ def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optiona if where(v): return lambda o: o.get(k, default) # type: ignore[union-attr] elif dataclasses.is_dataclass(obj): - for (field_name, _annotation) in obj.__annotations__.items(): + for field_name in obj.__annotations__.keys(): if where(getattr(obj, field_name)): return lambda o: getattr(o, field_name, default) elif is_namedtuple(obj): diff --git a/my/core/stats.py b/my/core/stats.py index aa05355..674a8d1 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -440,7 +440,7 @@ def _guess_datetime(x: Any) -> Optional[datetime]: d = asdict(x) except: # noqa: E722 bare except return None - for _k, v in d.items(): + for v in d.values(): if isinstance(v, datetime): return v return None diff --git a/my/polar.py b/my/polar.py index 9125f17..e52bb14 100644 --- a/my/polar.py +++ b/my/polar.py @@ -199,7 +199,7 @@ class Loader: def load_items(self, metas: Json) -> Iterable[Highlight]: - for _p, meta in metas.items(): + for _p, meta in metas.items(): # noqa: PERF102 with wrap(meta, throw=not config.defensive) as meta: yield from self.load_item(meta) diff --git a/ruff.toml b/ruff.toml index e7c6f07..2c9c39b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -10,6 +10,7 @@ lint.extend-select = [ "PLR", # 'refactor' rules "B", # 'bugbear' set -- various possible bugs + "PERF", # various potential performance speedups # "FA", # TODO enable later after we make sure cachew works? # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks @@ -65,4 +66,12 @@ lint.ignore = [ "B010", # same as above, but setattr "B017", # pytest.raises(Exception) "B023", # seems to result in false positives? + + # a bit too annoying, offers to convert for loops to list comprehension + # , which may heart readability + "PERF401", + + # suggests no using exception in for loops + # we do use this technique a lot, plus in 3.11 happy path exception handling is "zero-cost" + "PERF203", ] From 9fd4227abf7fa2619c9f1297e754eead0aee7fc3 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 02:50:05 +0100 Subject: [PATCH 23/55] ruff: enable RET/PIE/PLW --- my/coding/commits.py | 3 +- my/core/__main__.py | 10 ++--- my/core/_deprecated/kompress.py | 2 +- my/core/error.py | 3 +- my/core/orgmode.py | 3 +- my/core/query_range.py | 60 +++++++++++++------------- my/core/serialize.py | 3 +- my/core/util.py | 2 +- my/experimental/destructive_parsing.py | 2 +- my/location/fallback/via_home.py | 19 ++++---- my/photos/main.py | 3 +- my/smscalls.py | 7 ++- my/time/tz/via_location.py | 6 +-- ruff.toml | 32 ++++++++++---- 14 files changed, 80 insertions(+), 75 deletions(-) diff --git a/my/coding/commits.py b/my/coding/commits.py index 20b66a0..d4e05b7 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -187,8 +187,7 @@ def _repo_depends_on(_repo: Path) -> int: ff = _repo / pp if ff.exists(): return int(ff.stat().st_mtime) - else: - raise RuntimeError(f"Could not find a FETCH_HEAD/HEAD file in {_repo}") + raise RuntimeError(f"Could not find a FETCH_HEAD/HEAD file in {_repo}") def _commits(_repos: List[Path]) -> Iterator[Commit]: diff --git a/my/core/__main__.py b/my/core/__main__.py index c5e4552..8553942 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -43,7 +43,7 @@ def run_mypy(cfg_path: Path) -> Optional[CompletedProcess]: cmd = mypy_cmd() if cmd is None: return None - mres = run([ # noqa: UP022 + mres = run([ # noqa: UP022,PLW1510 *cmd, '--namespace-packages', '--color-output', # not sure if works?? @@ -214,10 +214,10 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module if len(errors) > 0: error(f'config check: {len(errors)} errors') return False - else: - # note: shouldn't exit here, might run something else - info('config check: success!') - return True + + # note: shouldn't exit here, might run something else + info('config check: success!') + return True from .util import HPIModule, modules diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 803e515..cd09c06 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -87,7 +87,7 @@ def kopen(path: PathIsh, *args, mode: str='rt', **kwargs) -> IO: elif name.endswith(Ext.lz4): import lz4.frame # type: ignore return lz4.frame.open(str(pp), mode, *args, **kwargs) - elif name.endswith(Ext.zstd) or name.endswith(Ext.zst): + elif name.endswith(Ext.zstd) or name.endswith(Ext.zst): # noqa: PIE810 kwargs['mode'] = mode return _zstd_open(pp, *args, **kwargs) elif name.endswith(Ext.targz): diff --git a/my/core/error.py b/my/core/error.py index e869614..ed26dda 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -41,8 +41,7 @@ def notnone(x: Optional[T]) -> T: def unwrap(res: Res[T]) -> T: if isinstance(res, Exception): raise res - else: - return res + return res def drop_exceptions(itr: Iterator[Res[T]]) -> Iterator[T]: diff --git a/my/core/orgmode.py b/my/core/orgmode.py index c70ded6..979f288 100644 --- a/my/core/orgmode.py +++ b/my/core/orgmode.py @@ -17,8 +17,7 @@ def parse_org_datetime(s: str) -> datetime: return datetime.strptime(s, fmt) except ValueError: continue - else: - raise RuntimeError(f"Bad datetime string {s}") + raise RuntimeError(f"Bad datetime string {s}") # TODO I guess want to borrow inspiration from bs4? element type <-> tag; and similar logic for find_one, find_all diff --git a/my/core/query_range.py b/my/core/query_range.py index 0a1b321..1f4a7ff 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -341,37 +341,37 @@ def select_range( if order_by_chosen is None: raise QueryException("""Can't order by range if we have no way to order_by! Specify a type or a key to order the value by""") - else: - # force drop_unsorted=True so we can use _create_range_filter - # sort the iterable by the generated order_by_chosen function - itr = select(itr, order_by=order_by_chosen, drop_unsorted=True) - filter_func: Optional[Where] - if order_by_value_type in [datetime, date]: - filter_func = _create_range_filter( - unparsed_range=unparsed_range, - end_parser=parse_datetime_float, - within_parser=parse_timedelta_float, - attr_func=order_by_chosen, # type: ignore[arg-type] - default_before=time.time(), - value_coercion_func=_datelike_to_float) - elif order_by_value_type in [int, float]: - # allow primitives to be converted using the default int(), float() callables - filter_func = _create_range_filter( - unparsed_range=unparsed_range, - end_parser=order_by_value_type, - within_parser=order_by_value_type, - attr_func=order_by_chosen, # type: ignore[arg-type] - default_before=None, - value_coercion_func=order_by_value_type) - else: - # TODO: add additional kwargs to let the user sort by other values, by specifying the parsers? - # would need to allow passing the end_parser, within parser, default before and value_coercion_func... - # (seems like a lot?) - raise QueryException("Sorting by custom types is currently unsupported") - # use the created filter function - # we've already applied drop_exceptions and kwargs related to unsortable values above - itr = select(itr, where=filter_func, limit=limit, reverse=reverse) + # force drop_unsorted=True so we can use _create_range_filter + # sort the iterable by the generated order_by_chosen function + itr = select(itr, order_by=order_by_chosen, drop_unsorted=True) + filter_func: Optional[Where] + if order_by_value_type in [datetime, date]: + filter_func = _create_range_filter( + unparsed_range=unparsed_range, + end_parser=parse_datetime_float, + within_parser=parse_timedelta_float, + attr_func=order_by_chosen, # type: ignore[arg-type] + default_before=time.time(), + value_coercion_func=_datelike_to_float) + elif order_by_value_type in [int, float]: + # allow primitives to be converted using the default int(), float() callables + filter_func = _create_range_filter( + unparsed_range=unparsed_range, + end_parser=order_by_value_type, + within_parser=order_by_value_type, + attr_func=order_by_chosen, # type: ignore[arg-type] + default_before=None, + value_coercion_func=order_by_value_type) + else: + # TODO: add additional kwargs to let the user sort by other values, by specifying the parsers? + # would need to allow passing the end_parser, within parser, default before and value_coercion_func... + # (seems like a lot?) + raise QueryException("Sorting by custom types is currently unsupported") + + # use the created filter function + # we've already applied drop_exceptions and kwargs related to unsortable values above + itr = select(itr, where=filter_func, limit=limit, reverse=reverse) else: # wrap_unsorted may be used here if the user specified an order_key, # or manually passed a order_value function diff --git a/my/core/serialize.py b/my/core/serialize.py index b196d47..ab11a20 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -145,8 +145,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: res = factory() if res is not None: return res - else: - raise RuntimeError("Should not happen!") + raise RuntimeError("Should not happen!") def dumps( diff --git a/my/core/util.py b/my/core/util.py index fb3edf8..a247f81 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -100,7 +100,7 @@ def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterabl def seen(p, m={}): # noqa: B006 if p in m: return True - m[p] = True + m[p] = True # noqa: RET503 for info in pkgutil.iter_modules(path, prefix): mname = info.name diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py index 056cc0b..b389f7e 100644 --- a/my/experimental/destructive_parsing.py +++ b/my/experimental/destructive_parsing.py @@ -35,7 +35,7 @@ def is_empty(x) -> bool: elif isinstance(x, list): return all(map(is_empty, x)) else: - assert_never(x) + assert_never(x) # noqa: RET503 class Manager: diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py index 199ebb0..e44c59d 100644 --- a/my/location/fallback/via_home.py +++ b/my/location/fallback/via_home.py @@ -92,13 +92,12 @@ def estimate_location(dt: DateExact) -> Iterator[FallbackLocation]: dt=datetime.fromtimestamp(d, timezone.utc), datasource='via_home') return - else: - # I guess the most reasonable is to fallback on the first location - lat, lon = hist[-1][1] - yield FallbackLocation( - lat=lat, - lon=lon, - accuracy=config.home_accuracy, - dt=datetime.fromtimestamp(d, timezone.utc), - datasource='via_home') - return + + # I guess the most reasonable is to fallback on the first location + lat, lon = hist[-1][1] + yield FallbackLocation( + lat=lat, + lon=lon, + accuracy=config.home_accuracy, + dt=datetime.fromtimestamp(d, timezone.utc), + datasource='via_home') diff --git a/my/photos/main.py b/my/photos/main.py index 63a6fea..c326405 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -43,8 +43,7 @@ class Photo(NamedTuple): for bp in config.paths: if self.path.startswith(bp): return self.path[len(bp):] - else: - raise RuntimeError(f"Weird path {self.path}, can't match against anything") + raise RuntimeError(f"Weird path {self.path}, can't match against anything") @property def name(self) -> str: diff --git a/my/smscalls.py b/my/smscalls.py index b56026d..78bf7ee 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -182,10 +182,9 @@ class MMS(NamedTuple): for (addr, _type) in self.addresses: if _type == 137: return addr - else: - # hmm, maybe return instead? but this probably shouldnt happen, means - # something is very broken - raise RuntimeError(f'No from address matching 137 found in {self.addresses}') + # hmm, maybe return instead? but this probably shouldnt happen, means + # something is very broken + raise RuntimeError(f'No from address matching 137 found in {self.addresses}') @property def from_me(self) -> bool: diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 156a5db..8f521e0 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -63,16 +63,14 @@ def _get_user_config(): except ImportError as ie: if "'time'" not in str(ie): raise ie - else: - return empty_config + return empty_config try: user_config = time.tz.via_location except AttributeError as ae: if not ("'tz'" in str(ae) or "'via_location'" in str(ae)): raise ae - else: - return empty_config + return empty_config return user_config diff --git a/ruff.toml b/ruff.toml index 2c9c39b..3cb9f76 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,18 +1,22 @@ target-version = "py38" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ - "F", # flakes rules -- default, but extend just in case - "E", # pycodestyle -- default, but extend just in case - "C4", # flake8-comprehensions -- unnecessary list/map/dict calls - "UP", # detect deprecated python stdlib stuff - "FBT", # detect use of boolean arguments - "RUF", # various ruff-specific rules - "PLR", # 'refactor' rules - "B", # 'bugbear' set -- various possible bugs - + "F", # flakes rules -- default, but extend just in case + "E", # pycodestyle -- default, but extend just in case + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "UP", # detect deprecated python stdlib stuff + "FBT", # detect use of boolean arguments + "RUF", # various ruff-specific rules + "PLR", # 'refactor' rules + "B", # 'bugbear' set -- various possible bugs "PERF", # various potential performance speedups + "RET", # early returns + "PIE", # 'misc' lints + "PLW", # pylint warnings # "FA", # TODO enable later after we make sure cachew works? + # "PTH", # pathlib migration -- TODO enable later # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later + # "A", # TODO builtin shadowing -- handle later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives ] @@ -67,6 +71,10 @@ lint.ignore = [ "B017", # pytest.raises(Exception) "B023", # seems to result in false positives? + # complains about useless pass, but has sort of a false positive if the function has a docstring? + # this is common for click entrypoints (e.g. in __main__), so disable + "PIE790", + # a bit too annoying, offers to convert for loops to list comprehension # , which may heart readability "PERF401", @@ -74,4 +82,10 @@ lint.ignore = [ # suggests no using exception in for loops # we do use this technique a lot, plus in 3.11 happy path exception handling is "zero-cost" "PERF203", + + "RET504", # unnecessary assignment before returning -- that can be useful for readability + "RET505", # unnecessary else after return -- can hurt readability + + "PLW0603", # global variable update.. we usually know why we are doing this + "PLW2901", # for loop variable overwritten, usually this is intentional ] From ac08af7aabc09d6fd28f44ba0c155c62382cf96f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 02:54:26 +0100 Subject: [PATCH 24/55] ruff: enable PT (pytest) rules --- ruff.toml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ruff.toml b/ruff.toml index 3cb9f76..cb9445f 100644 --- a/ruff.toml +++ b/ruff.toml @@ -13,12 +13,17 @@ lint.extend-select = [ "RET", # early returns "PIE", # 'misc' lints "PLW", # pylint warnings + "PT", # pytest stuff # "FA", # TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later # "A", # TODO builtin shadowing -- handle later # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives + # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying + # "FIX", # complains about fixmes/todos -- annoying + # "TD", # complains about todo formatting -- too annoying + # "ALL", ] lint.ignore = [ @@ -88,4 +93,8 @@ lint.ignore = [ "PLW0603", # global variable update.. we usually know why we are doing this "PLW2901", # for loop variable overwritten, usually this is intentional + + "PT004", # deprecated rule, will be removed later + "PT011", # pytest raises should is too broad + "PT012", # pytest raises should contain a single statement ] From c5df3ce1284d3730e6650321a4fe0c922960954f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:05:24 +0100 Subject: [PATCH 25/55] ruff: enable W, COM, EXE rules --- my/bluemaestro.py | 1 - my/coding/commits.py | 2 +- my/core/discovery_pure.py | 2 +- my/fbmessenger/android.py | 2 +- my/jawbone/__init__.py | 2 +- my/media/imdb.py | 1 - my/rtm.py | 2 +- my/telegram/telegram_backup.py | 2 +- ruff.toml | 19 +++++++++++++------ 9 files changed, 19 insertions(+), 14 deletions(-) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 5d0968b..4c33fd1 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -1,4 +1,3 @@ -#!/usr/bin/python3 """ [[https://bluemaestro.com/products/product-details/bluetooth-environmental-monitor-and-logger][Bluemaestro]] temperature/humidity/pressure monitor """ diff --git a/my/coding/commits.py b/my/coding/commits.py index d4e05b7..9661ae5 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -136,7 +136,7 @@ def canonical_name(repo: Path) -> str: # else: # rname = r.name # if 'backups/github' in repo: - # pass # TODO + # pass # TODO def _fd_path() -> str: diff --git a/my/core/discovery_pure.py b/my/core/discovery_pure.py index 63d9922..b753de8 100644 --- a/my/core/discovery_pure.py +++ b/my/core/discovery_pure.py @@ -242,7 +242,7 @@ def test_pure() -> None: src = Path(__file__).read_text() # 'import my' is allowed, but # dont allow anything other HPI modules - assert re.findall('import ' + r'my\.\S+', src, re.M) == [] + assert re.findall('import ' + r'my\.\S+', src, re.MULTILINE) == [] assert 'from ' + 'my' not in src diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index bc06114..7e48c78 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -228,7 +228,7 @@ def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]: for r in db.execute( ''' - SELECT *, json_extract(sender, "$.user_key") AS user_key FROM messages + SELECT *, json_extract(sender, "$.user_key") AS user_key FROM messages WHERE msg_type NOT IN ( -1, /* these don't have any data at all, likely immediately deleted or something? */ 2 /* these are 'left group' system messages, also a bit annoying since they might reference nonexistent users */ diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index affe230..35112ba 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -239,7 +239,7 @@ def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True): # axes.title.set_size(10) if showtext: - axes.text(xlims[1] - timedelta(hours=1.5), 20, str(sleep),) + axes.text(xlims[1] - timedelta(hours=1.5), 20, str(sleep)) # plt.text(sleep.asleep(), 0, hhmm(sleep.asleep())) diff --git a/my/media/imdb.py b/my/media/imdb.py index c66f5dc..df31032 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 import csv from datetime import datetime from typing import Iterator, List, NamedTuple diff --git a/my/rtm.py b/my/rtm.py index 22752fe..b559ba4 100644 --- a/my/rtm.py +++ b/my/rtm.py @@ -58,7 +58,7 @@ class MyTodo: def get_status(self) -> str: if 'STATUS' not in self.todo: return None # type: ignore - # TODO 'COMPLETED'? + # TODO 'COMPLETED'? return str(self.todo['STATUS']) # TODO tz? diff --git a/my/telegram/telegram_backup.py b/my/telegram/telegram_backup.py index 0617501..ff4f904 100644 --- a/my/telegram/telegram_backup.py +++ b/my/telegram/telegram_backup.py @@ -18,7 +18,7 @@ from my.config import telegram as user_config class config(user_config.telegram_backup): # path to the export database.sqlite export_path: PathIsh - + @dataclass class Chat: diff --git a/ruff.toml b/ruff.toml index cb9445f..8cbc642 100644 --- a/ruff.toml +++ b/ruff.toml @@ -3,17 +3,22 @@ target-version = "py38" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ "F", # flakes rules -- default, but extend just in case "E", # pycodestyle -- default, but extend just in case - "C4", # flake8-comprehensions -- unnecessary list/map/dict calls - "UP", # detect deprecated python stdlib stuff - "FBT", # detect use of boolean arguments - "RUF", # various ruff-specific rules - "PLR", # 'refactor' rules + "W", # various warnings + "B", # 'bugbear' set -- various possible bugs + "C4", # flake8-comprehensions -- unnecessary list/map/dict calls + "COM", # trailing commas + "EXE", # various checks wrt executable files + "FBT", # detect use of boolean arguments + "FURB", # various rules "PERF", # various potential performance speedups - "RET", # early returns "PIE", # 'misc' lints + "PLR", # 'refactor' rules "PLW", # pylint warnings "PT", # pytest stuff + "RET", # early returns + "RUF", # various ruff-specific rules + "UP", # detect deprecated python stdlib stuff # "FA", # TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later @@ -97,4 +102,6 @@ lint.ignore = [ "PT004", # deprecated rule, will be removed later "PT011", # pytest raises should is too broad "PT012", # pytest raises should contain a single statement + + "COM812", # trailing comma missing -- TODO maybe use this? ] From fc0e0be291795970cec45209e9249d893d5173cc Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:09:32 +0100 Subject: [PATCH 26/55] ruff: enable ICN and PD rules --- my/body/weight.py | 2 +- my/emfit/__init__.py | 4 ++-- ruff.toml | 4 ++++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/my/body/weight.py b/my/body/weight.py index 277b4d1..51e6513 100644 --- a/my/body/weight.py +++ b/my/body/weight.py @@ -83,7 +83,7 @@ def make_dataframe(data: Iterator[Result]): } df = pd.DataFrame(it()) - df.set_index('dt', inplace=True) + df = df.set_index('dt') # TODO not sure about UTC?? df.index = pd.to_datetime(df.index, utc=True) return df diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 71a483f..9934903 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -155,9 +155,9 @@ def dataframe() -> DataFrameT: last = s # meh dicts.append(d) - import pandas + import pandas as pd - return pandas.DataFrame(dicts) + return pd.DataFrame(dicts) def stats() -> Stats: diff --git a/ruff.toml b/ruff.toml index 8cbc642..c2c88ef 100644 --- a/ruff.toml +++ b/ruff.toml @@ -9,9 +9,11 @@ lint.extend-select = [ "C4", # flake8-comprehensions -- unnecessary list/map/dict calls "COM", # trailing commas "EXE", # various checks wrt executable files + "ICN", # various import conventions "FBT", # detect use of boolean arguments "FURB", # various rules "PERF", # various potential performance speedups + "PD", # pandas rules "PIE", # 'misc' lints "PLR", # 'refactor' rules "PLW", # pylint warnings @@ -104,4 +106,6 @@ lint.ignore = [ "PT012", # pytest raises should contain a single statement "COM812", # trailing comma missing -- TODO maybe use this? + + "PD901", # generic variable name df ] From affa79ba3ae0aee53eb908dffdeee88800215c45 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:14:23 +0100 Subject: [PATCH 27/55] my.time.tz.via_location: fix accidental RuntimeError introduced in previous MR --- my/time/tz/via_location.py | 1 - 1 file changed, 1 deletion(-) diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 8f521e0..4920333 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -104,7 +104,6 @@ def _timezone_finder(*, fast: bool) -> Any: # for backwards compatibility def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: try: - raise RuntimeError import my.location.all for loc in my.location.all.locations(): From 1c5efc46aa18ebfb8fdb5ccbfde03b731e5355bf Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:18:45 +0100 Subject: [PATCH 28/55] ruff: enable TRY rules --- my/core/_deprecated/kompress.py | 3 ++- my/core/time.py | 3 ++- ruff.toml | 7 +++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index cd09c06..1cd2636 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -141,9 +141,10 @@ open = kopen # TODO deprecate def kexists(path: PathIsh, subpath: str) -> bool: try: kopen(path, subpath) - return True except Exception: return False + else: + return True import zipfile diff --git a/my/core/time.py b/my/core/time.py index 5a47c3d..6de4105 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -11,10 +11,11 @@ def user_forced() -> Sequence[str]: # https://stackoverflow.com/questions/36067621/python-all-possible-timezone-abbreviations-for-given-timezone-name-and-vise-ve try: from my.config import time as user_config - return user_config.tz.force_abbreviations # type: ignore[attr-defined] except: # todo log/apply policy return [] + else: + return user_config.tz.force_abbreviations # type: ignore[attr-defined] @lru_cache(1) diff --git a/ruff.toml b/ruff.toml index c2c88ef..9a932ef 100644 --- a/ruff.toml +++ b/ruff.toml @@ -20,6 +20,7 @@ lint.extend-select = [ "PT", # pytest stuff "RET", # early returns "RUF", # various ruff-specific rules + "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff # "FA", # TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later @@ -108,4 +109,10 @@ lint.ignore = [ "COM812", # trailing comma missing -- TODO maybe use this? "PD901", # generic variable name df + + "TRY003", # suggests defining exception messages in exception class -- kinda annoying + "TRY004", # prefer TypeError -- don't see the point + "TRY201", # raise without specifying exception name -- sometimes hurts readability + "TRY400", # TODO double check this, might be useful + "TRY401", # redundant exception in logging.exception call? TODO double check, might result in excessive logging ] From d58453410c34d75715b71c041f7a58a4f0954436 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 28 Aug 2024 03:58:28 +0100 Subject: [PATCH 29/55] ruff: process remaining existing checks and suppress the annoying ones --- my/coding/commits.py | 4 ++-- my/core/_deprecated/kompress.py | 2 +- my/core/common.py | 2 +- my/core/hpi_compat.py | 2 +- my/photos/main.py | 2 +- ruff.toml | 34 +++++++++++++++++++++++++++++++-- 6 files changed, 38 insertions(+), 8 deletions(-) diff --git a/my/coding/commits.py b/my/coding/commits.py index 9661ae5..31c366e 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -178,12 +178,12 @@ def repos() -> List[Path]: # returns modification time for an index to use as hash function def _repo_depends_on(_repo: Path) -> int: - for pp in { + for pp in [ ".git/FETCH_HEAD", ".git/HEAD", "FETCH_HEAD", # bare "HEAD", # bare - }: + ]: ff = _repo / pp if ff.exists(): return int(ff.stat().st_mtime) diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 1cd2636..63ce523 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -27,7 +27,7 @@ class Ext: def is_compressed(p: Path) -> bool: # todo kinda lame way for now.. use mime ideally? # should cooperate with kompress.kopen? - return any(p.name.endswith(ext) for ext in {Ext.xz, Ext.zip, Ext.lz4, Ext.zstd, Ext.zst, Ext.targz}) + return any(p.name.endswith(ext) for ext in [Ext.xz, Ext.zip, Ext.lz4, Ext.zstd, Ext.zst, Ext.targz]) def _zstd_open(path: Path, *args, **kwargs) -> IO: diff --git a/my/core/common.py b/my/core/common.py index 5f8d03a..a2c2ad3 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -14,7 +14,7 @@ from typing import ( ) from . import compat -from . import warnings as warnings +from . import warnings # some helper functions # TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 9330e49..6261c23 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -123,7 +123,7 @@ class always_supports_sequence(Iterator[V]): self.it = it self._list: Optional[List] = None - def __iter__(self) -> Iterator[V]: + def __iter__(self) -> Iterator[V]: # noqa: PYI034 return self.it.__iter__() def __next__(self) -> V: diff --git a/my/photos/main.py b/my/photos/main.py index c326405..bf912e4 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -65,7 +65,7 @@ def _make_photo_aux(*args, **kwargs) -> List[Result]: def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Iterator[Result]: exif: Exif - if any(x in mtype for x in {'image/png', 'image/x-ms-bmp', 'video'}): + if any(x in mtype for x in ['image/png', 'image/x-ms-bmp', 'video']): # TODO don't remember why.. logger.debug(f"skipping exif extraction for {photo} due to mime {mtype}") exif = {} diff --git a/ruff.toml b/ruff.toml index 9a932ef..0d3bb16 100644 --- a/ruff.toml +++ b/ruff.toml @@ -15,11 +15,15 @@ lint.extend-select = [ "PERF", # various potential performance speedups "PD", # pandas rules "PIE", # 'misc' lints - "PLR", # 'refactor' rules + "PLC", # pylint convention rules + "PLR", # pylint refactor rules "PLW", # pylint warnings "PT", # pytest stuff + "PYI", # various type hinting rules "RET", # early returns "RUF", # various ruff-specific rules + "TID", # various imports suggestions + "TCH", # various type checking rules "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff # "FA", # TODO enable later after we make sure cachew works? @@ -31,10 +35,15 @@ lint.extend-select = [ # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying # "FIX", # complains about fixmes/todos -- annoying # "TD", # complains about todo formatting -- too annoying - # "ALL", + # "ANN", # missing type annotations? seems way to string though + + # "ALL", # uncomment this to check for new rules! ] lint.ignore = [ + "D", # annoying nags about docstrings + "N", # pep naming + ### too opinionated style checks "E501", # too long lines "E702", # Multiple statements on one line (semicolon) @@ -115,4 +124,25 @@ lint.ignore = [ "TRY201", # raise without specifying exception name -- sometimes hurts readability "TRY400", # TODO double check this, might be useful "TRY401", # redundant exception in logging.exception call? TODO double check, might result in excessive logging + + "TCH002", # suggests moving imports into type checking blocks -- too annoying + "TCH003", # suggests moving imports into type checking blocks -- too annoying + + "I001", # unsorted import block TODO consider these? + "PGH", # TODO force error code in mypy instead + + # TODO enable TID? + "TID252", # Prefer absolute imports over relative imports from parent modules + + ## too annoying + "T20", # just complains about prints and pprints + "Q", # flake quotes, too annoying + "C90", # some complexity checking + "G004", # logging statement uses f string + "ERA001", # commented out code + "SLF001", # private member accessed + "BLE001", # do not catch 'blind' Exception + "INP001", # complains about implicit namespace packages + "SIM", # some if statements crap + ## ] From 71fdeca5e10d99526b39d7cbd1eb8bd5aa43cbf9 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 31 Aug 2024 02:03:22 +0100 Subject: [PATCH 30/55] ci: update mypy config and make ruff config more consistent with other projects --- my/coding/github.py | 2 +- my/config.py | 2 +- my/core/__main__.py | 2 +- my/core/_deprecated/kompress.py | 2 +- my/core/tests/test_config.py | 1 - my/core/utils/concurrent.py | 2 +- my/demo.py | 1 - my/endomondo.py | 2 +- my/foursquare.py | 1 - my/hackernews/common.py | 2 +- my/jawbone/plots.py | 1 - mypy.ini | 9 ++----- ruff.toml | 43 ++++++++++++++++++--------------- 13 files changed, 32 insertions(+), 38 deletions(-) diff --git a/my/coding/github.py b/my/coding/github.py index de64f05..c495554 100644 --- a/my/coding/github.py +++ b/my/coding/github.py @@ -6,7 +6,7 @@ warnings.high('my.coding.github is deprecated! Please use my.github.all instead! # todo why aren't DeprecationWarning shown by default?? if not TYPE_CHECKING: - from ..github.all import events, get_events + from ..github.all import events, get_events # noqa: F401 # todo deprecate properly iter_events = events diff --git a/my/config.py b/my/config.py index a92b2bc..2dd9cda 100644 --- a/my/config.py +++ b/my/config.py @@ -10,7 +10,7 @@ This file is used for: - for loading the actual user config ''' #### NOTE: you won't need this line VVVV in your personal config -from my.core import init +from my.core import init # noqa: F401 ### diff --git a/my/core/__main__.py b/my/core/__main__.py index 8553942..c675676 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -577,7 +577,7 @@ def query_hpi_functions( # output == 'repl' eprint(f"\nInteract with the results by using the {click.style('res', fg='green')} variable\n") try: - import IPython # type: ignore[import] + import IPython # type: ignore[import,unused-ignore] except ModuleNotFoundError: eprint("'repl' typically uses ipython, install it with 'python3 -m pip install ipython'. falling back to stdlib...") import code diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index 63ce523..b08f04b 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -120,7 +120,7 @@ class CPath(BasePath): Path only has _accessor and _closed slots, so can't directly set .open method _accessor.open has to return file descriptor, doesn't work for compressed stuff. """ - def open(self, *args, **kwargs): + def open(self, *args, **kwargs): # noqa: ARG002 kopen_kwargs = {} mode = kwargs.get('mode') if mode is not None: diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py index a318a95..78d1a62 100644 --- a/my/core/tests/test_config.py +++ b/my/core/tests/test_config.py @@ -8,7 +8,6 @@ from pathlib import Path import pytest import pytz -from more_itertools import ilen import my.config from my.core import notnone diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 5f11ab0..146861b 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -47,5 +47,5 @@ class DummyExecutor(Executor): return f - def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002 + def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002,ARG002 self._shutdown = True diff --git a/my/demo.py b/my/demo.py index e27b5dd..0c54792 100644 --- a/my/demo.py +++ b/my/demo.py @@ -3,7 +3,6 @@ Just a demo module for testing and documentation purposes ''' import json -from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timezone, tzinfo from pathlib import Path diff --git a/my/endomondo.py b/my/endomondo.py index 1d7acc2..293a542 100644 --- a/my/endomondo.py +++ b/my/endomondo.py @@ -31,7 +31,7 @@ def inputs() -> Sequence[Path]: # todo add a doctor check for pip endoexport module import endoexport.dal as dal -from endoexport.dal import Point, Workout +from endoexport.dal import Point, Workout # noqa: F401 from .core import Res diff --git a/my/foursquare.py b/my/foursquare.py index 63e1837..394fdf3 100644 --- a/my/foursquare.py +++ b/my/foursquare.py @@ -4,7 +4,6 @@ Foursquare/Swarm checkins from datetime import datetime, timezone, timedelta from itertools import chain -from pathlib import Path import json # TODO pytz for timezone??? diff --git a/my/hackernews/common.py b/my/hackernews/common.py index 0c5ff9b..6990987 100644 --- a/my/hackernews/common.py +++ b/my/hackernews/common.py @@ -1,6 +1,6 @@ from typing import Protocol -from my.core import datetime_aware, Json +from my.core import datetime_aware def hackernews_link(id: str) -> str: diff --git a/my/jawbone/plots.py b/my/jawbone/plots.py index 5dcb63d..d26d606 100755 --- a/my/jawbone/plots.py +++ b/my/jawbone/plots.py @@ -3,7 +3,6 @@ from pathlib import Path # from kython.plotting import * from csv import DictReader -from itertools import islice from typing import Dict, Any, NamedTuple diff --git a/mypy.ini b/mypy.ini index ebc81a5..9c34fcc 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,18 +1,13 @@ [mypy] -namespace_packages = True pretty = True show_error_context = True -show_error_codes = True show_column_numbers = True show_error_end = True +warn_redundant_casts = True warn_unused_ignores = True check_untyped_defs = True -enable_error_code = possibly-undefined strict_equality = True - -# a bit annoying, it has optional ipython import which should be ignored in mypy-core configuration.. -[mypy-my.core.__main__] -warn_unused_ignores = False +enable_error_code = possibly-undefined # todo ok, maybe it wasn't such a good idea.. # mainly because then tox picks it up and running against the user config, not the repository config diff --git a/ruff.toml b/ruff.toml index 0d3bb16..5fbd657 100644 --- a/ruff.toml +++ b/ruff.toml @@ -9,6 +9,7 @@ lint.extend-select = [ "C4", # flake8-comprehensions -- unnecessary list/map/dict calls "COM", # trailing commas "EXE", # various checks wrt executable files + # "I", # sort imports "ICN", # various import conventions "FBT", # detect use of boolean arguments "FURB", # various rules @@ -23,26 +24,26 @@ lint.extend-select = [ "RET", # early returns "RUF", # various ruff-specific rules "TID", # various imports suggestions - "TCH", # various type checking rules "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff - # "FA", # TODO enable later after we make sure cachew works? + # "FA", # suggest using from __future__ import annotations TODO enable later after we make sure cachew works? # "PTH", # pathlib migration -- TODO enable later - # "ARG", # TODO useful, but results in some false positives in pytest fixtures... maybe later - # "A", # TODO builtin shadowing -- handle later - # "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks - # "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives + "ARG", # unused argument checks + # "A", # builtin shadowing -- TODO handle later # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying - # "FIX", # complains about fixmes/todos -- annoying - # "TD", # complains about todo formatting -- too annoying - # "ANN", # missing type annotations? seems way to string though # "ALL", # uncomment this to check for new rules! ] lint.ignore = [ - "D", # annoying nags about docstrings - "N", # pep naming + "D", # annoying nags about docstrings + "N", # pep naming + "TCH", # type checking rules, mostly just suggests moving imports under TYPE_CHECKING + "S", # bandit (security checks) -- tends to be not very useful, lots of nitpicks + "DTZ", # datetimes checks -- complaining about missing tz and mostly false positives + "FIX", # complains about fixmes/todos -- annoying + "TD", # complains about todo formatting -- too annoying + "ANN", # missing type annotations? seems way to strict though ### too opinionated style checks "E501", # too long lines @@ -62,10 +63,9 @@ lint.ignore = [ "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 + # 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 - "F401", # imported but unused ### ### TODO should be fine to use these with from __future__ import annotations? @@ -90,8 +90,10 @@ lint.ignore = [ "B009", # calling gettattr with constant attribute -- this is useful to convince mypy "B010", # same as above, but setattr + "B011", # complains about assert False "B017", # pytest.raises(Exception) "B023", # seems to result in false positives? + "B028", # suggest using explicit stacklevel? TODO double check later, but not sure it's useful # complains about useless pass, but has sort of a false positive if the function has a docstring? # this is common for click entrypoints (e.g. in __main__), so disable @@ -115,7 +117,7 @@ lint.ignore = [ "PT011", # pytest raises should is too broad "PT012", # pytest raises should contain a single statement - "COM812", # trailing comma missing -- TODO maybe use this? + "COM812", # trailing comma missing -- mostly just being annoying with long multiline strings "PD901", # generic variable name df @@ -125,15 +127,12 @@ lint.ignore = [ "TRY400", # TODO double check this, might be useful "TRY401", # redundant exception in logging.exception call? TODO double check, might result in excessive logging - "TCH002", # suggests moving imports into type checking blocks -- too annoying - "TCH003", # suggests moving imports into type checking blocks -- too annoying - - "I001", # unsorted import block TODO consider these? "PGH", # TODO force error code in mypy instead - # TODO enable TID? "TID252", # Prefer absolute imports over relative imports from parent modules + "UP038", # suggests using | (union) in isisntance checks.. but it results in slower code + ## too annoying "T20", # just complains about prints and pprints "Q", # flake quotes, too annoying @@ -144,5 +143,9 @@ lint.ignore = [ "BLE001", # do not catch 'blind' Exception "INP001", # complains about implicit namespace packages "SIM", # some if statements crap + "RSE102", # complains about missing parens in exceptions ## + + "ARG001", # ugh, kinda annoying when using pytest fixtures + "F401" , # TODO nice to have, but annoying with NOT_HPI_MODULE thing ] From 27178c09398939d01803e27fcc28d0cefa6d1422 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Fri, 13 Sep 2024 01:18:40 +0100 Subject: [PATCH 31/55] my.google.takeout.parser: speedup event merging on newer google_takeout_parser versions --- my/google/takeout/parser.py | 19 +++++++++++++++---- my/youtube/takeout.py | 12 ++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 258ab96..170553a 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -31,6 +31,7 @@ ABBR_TIMEZONES.extend(user_forced()) import google_takeout_parser from google_takeout_parser.path_dispatch import TakeoutParser from google_takeout_parser.merge import GoogleEventSet, CacheResults +from google_takeout_parser.models import BaseEvent # see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example from my.config import google as user_config @@ -95,6 +96,17 @@ def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: error_policy = config.error_policy count = 0 emitted = GoogleEventSet() + + try: + emitted_add = emitted.add_if_not_present + except AttributeError: + # compat for older versions of google_takeout_parser which didn't have this method + def emitted_add(other: BaseEvent) -> bool: + if other in emitted: + return False + emitted.add(other) + return True + # reversed shouldn't really matter? but logic is to use newer # takeouts if they're named according to date, since JSON Activity # is nicer than HTML Activity @@ -123,10 +135,9 @@ def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: elif error_policy == 'drop': pass continue - if event in emitted: - continue - emitted.add(event) - yield event # type: ignore[misc] + + if emitted_add(event): + yield event # type: ignore[misc] logger.debug( f"HPI Takeout merge: from a total of {count} events, removed {count - len(emitted)} duplicates" ) diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 99d65d9..284c082 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -1,10 +1,10 @@ from typing import NamedTuple, List, Iterable, TYPE_CHECKING -from ..core import datetime_aware, Res, LazyLogger -from ..core.compat import removeprefix +from my.core import datetime_aware, make_logger, stat, Res, Stats +from my.core.compat import deprecated, removeprefix -logger = LazyLogger(__name__) +logger = make_logger(__name__) class Watched(NamedTuple): @@ -93,7 +93,6 @@ def watched() -> Iterable[Res[Watched]]: ) -from ..core import stat, Stats def stats() -> Stats: return stat(watched) @@ -101,8 +100,9 @@ def stats() -> Stats: ### deprecated stuff (keep in my.media.youtube) if not TYPE_CHECKING: - # "deprecate" by hiding from mypy - get_watched = watched + @deprecated("use 'watched' instead") + def get_watched(*args, **kwargs): + return watched(*args, **kwargs) def _watched_legacy() -> Iterable[Watched]: From 201ddd4d7c45f63f3e3196f6b9be22402822680d Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 16 Sep 2024 23:41:58 +0100 Subject: [PATCH 32/55] my.core.structure: add support for .tar.gz archives this will be useful to migrate .tar.gz processing to kompress in a backwards compatible way, or to run them against unpacked folder structure if user prefers --- my/core/structure.py | 47 +++++++++++------- my/core/tests/structure.py | 7 +-- .../tests/structure_data/gdpr_export.tar.gz | Bin 0 -> 349 bytes 3 files changed, 33 insertions(+), 21 deletions(-) create mode 100644 my/core/tests/structure_data/gdpr_export.tar.gz diff --git a/my/core/structure.py b/my/core/structure.py index be5b307..fa26532 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -1,6 +1,8 @@ import atexit import os import shutil +import sys +import tarfile import tempfile import zipfile from contextlib import contextmanager @@ -34,6 +36,7 @@ def _structure_exists(base_dir: Path, paths: Sequence[str], *, partial: bool = F ZIP_EXT = {".zip"} +TARGZ_EXT = {".tar.gz"} @contextmanager @@ -44,7 +47,7 @@ def match_structure( partial: bool = False, ) -> Generator[Tuple[Path, ...], None, None]: """ - Given a 'base' directory or zipfile, recursively search for one or more paths that match the + Given a 'base' directory or archive (zip/tar.gz), recursively search for one or more paths that match the pattern described in 'expected'. That can be a single string, or a list of relative paths (as strings) you expect at the same directory. @@ -52,12 +55,12 @@ def match_structure( expected be present, not all of them. This reduces the chances of the user misconfiguring gdpr exports, e.g. - if they zipped the folders instead of the parent directory or vice-versa + if they archived the folders instead of the parent directory or vice-versa When this finds a matching directory structure, it stops searching in that subdirectory and continues onto other possible subdirectories which could match - If base is a zipfile, this extracts the zipfile into a temporary directory + If base is an archive, this extracts it into a temporary directory (configured by core_config.config.get_tmp_dir), and then searches the extracted folder for matching structures @@ -93,12 +96,12 @@ def match_structure( This doesn't require an exhaustive list of expected values, but its a good idea to supply a complete picture of the expected structure to avoid false-positives - This does not recursively unzip zipfiles in the subdirectories, - it only unzips into a temporary directory if 'base' is a zipfile + This does not recursively decompress archives in the subdirectories, + it only unpacks into a temporary directory if 'base' is an archive A common pattern for using this might be to use get_files to get a list - of zipfiles or top-level gdpr export directories, and use match_structure - to search the resulting paths for a export structure you're expecting + of archives or top-level gdpr export directories, and use match_structure + to search the resulting paths for an export structure you're expecting """ from . import core_config as CC @@ -108,26 +111,34 @@ def match_structure( expected = (expected,) is_zip: bool = base.suffix in ZIP_EXT + is_targz: bool = any(base.name.endswith(suffix) for suffix in TARGZ_EXT) searchdir: Path = base.absolute() try: - # if the file given by the user is a zipfile, create a temporary - # directory and extract the zipfile to that temporary directory + # if the file given by the user is an archive, create a temporary + # directory and extract it to that temporary directory # # this temporary directory is removed in the finally block - if is_zip: + if is_zip or is_targz: # sanity check before we start creating directories/rm-tree'ing things - assert base.exists(), f"zipfile at {base} doesn't exist" + assert base.exists(), f"archive at {base} doesn't exist" searchdir = Path(tempfile.mkdtemp(dir=tdir)) - # base might already be a ZipPath, and str(base) would end with / - zf = zipfile.ZipFile(str(base).rstrip('/')) - zf.extractall(path=str(searchdir)) - + if is_zip: + # base might already be a ZipPath, and str(base) would end with / + zf = zipfile.ZipFile(str(base).rstrip('/')) + zf.extractall(path=str(searchdir)) + elif is_targz: + with tarfile.open(str(base)) as tar: + # filter is a security feature, will be required param in later python version + mfilter = {'filter': 'data'} if sys.version_info[:2] >= (3, 12) else {} + tar.extractall(path=str(searchdir), **mfilter) # type: ignore[arg-type] + else: + raise RuntimeError("can't happen") else: if not searchdir.is_dir(): - raise NotADirectoryError(f"Expected either a zipfile or a directory, received {searchdir}") + raise NotADirectoryError(f"Expected either a zip/tar.gz archive or a directory, received {searchdir}") matches: List[Path] = [] possible_targets: List[Path] = [searchdir] @@ -150,9 +161,9 @@ def match_structure( finally: - if is_zip: + if is_zip or is_targz: # make sure we're not mistakenly deleting data - assert str(searchdir).startswith(str(tdir)), f"Expected the temporary directory for extracting zip to start with the temporary directory prefix ({tdir}), found {searchdir}" + assert str(searchdir).startswith(str(tdir)), f"Expected the temporary directory for extracting archive to start with the temporary directory prefix ({tdir}), found {searchdir}" shutil.rmtree(str(searchdir)) diff --git a/my/core/tests/structure.py b/my/core/tests/structure.py index 6a94fc4..741e0ea 100644 --- a/my/core/tests/structure.py +++ b/my/core/tests/structure.py @@ -14,8 +14,9 @@ def test_gdpr_structure_exists() -> None: assert results == (structure_data / "gdpr_subdirs" / "gdpr_export",) -def test_gdpr_unzip() -> None: - with match_structure(structure_data / "gdpr_export.zip", expected=gdpr_expected) as results: +@pytest.mark.parametrize("archive", ["gdpr_export.zip", "gdpr_export.tar.gz"]) +def test_gdpr_unpack(archive: str) -> None: + with match_structure(structure_data / archive, expected=gdpr_expected) as results: assert len(results) == 1 extracted = results[0] index_file = extracted / "messages" / "index.csv" @@ -32,6 +33,6 @@ def test_match_partial() -> None: def test_not_directory() -> None: - with pytest.raises(NotADirectoryError, match=r"Expected either a zipfile or a directory"): + with pytest.raises(NotADirectoryError, match=r"Expected either a zip/tar.gz archive or a directory"): with match_structure(structure_data / "messages/index.csv", expected=gdpr_expected): pass diff --git a/my/core/tests/structure_data/gdpr_export.tar.gz b/my/core/tests/structure_data/gdpr_export.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..4f0597cdc7f3aa062ae896786375c5df87d49ec0 GIT binary patch literal 349 zcmV-j0iymNiwFP!000021MQgYZh|lrhWmS0!4+sf=;`GcgpM$UlC~O?W%s_i%*2^Y zXFZ&OZgnulN@i{zdo#NJi2B!+HOBA;|M`W&T_3Tv6*Z`7g2m&BlMz zRr;_f-9Fy`jr_m#&-tr{*NS^|K6I{W~;~O0r%hkN&(*g^YHJq_f1z1i2s=UmlQDnG5?Wd^FP|(pSb=n v1m^!d{15&6^N0Ko&VTw3+YIx63cPkc`*w{t0fHb1f; Date: Wed, 18 Sep 2024 23:03:03 +0100 Subject: [PATCH 33/55] my.github.gdpr/my.zulip.organization: use kompress support for tar.gz if it's available otherwise fall back onto unpacking into tmp dir via my.core.structure --- my/core/kompress.py | 6 +-- my/github/gdpr.py | 106 +++++++++++++++++++++++---------------- my/zulip/organization.py | 91 ++++++++++++++++++++++----------- setup.py | 14 +++--- 4 files changed, 135 insertions(+), 82 deletions(-) diff --git a/my/core/kompress.py b/my/core/kompress.py index 6ab3228..7cbf310 100644 --- a/my/core/kompress.py +++ b/my/core/kompress.py @@ -1,4 +1,5 @@ from .internal import assert_subpackage; assert_subpackage(__name__) + from . import warnings # do this later -- for now need to transition modules to avoid using kompress directly (e.g. ZipPath) @@ -8,10 +9,7 @@ try: from kompress import * except ModuleNotFoundError as e: if e.name == 'kompress': - warnings.high('Please install kompress (pip3 install kompress), it will be required in the future. Falling onto vendorized kompress for now.') + warnings.high('Please install kompress (pip3 install kompress). Falling onto vendorized kompress for now.') from ._deprecated.kompress import * # type: ignore[assignment] else: raise e - -# this is deprecated in compress, keep here for backwards compatibility -open = kopen # noqa: F405 diff --git a/my/github/gdpr.py b/my/github/gdpr.py index acbeb8f..a56ff46 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -1,36 +1,42 @@ """ Github data (uses [[https://github.com/settings/admin][official GDPR export]]) """ -from dataclasses import dataclass + +from __future__ import annotations + import json +from abc import abstractmethod from pathlib import Path -import tarfile -from typing import Iterable, Any, Sequence, Dict, Optional +from typing import Any, Iterator, Sequence -from my.core import get_files, Res, PathIsh, stat, Stats, make_logger -from my.core.cfg import make_config -from my.core.error import notnone, echain - -from .common import Event, parse_dt, EventIds - -# TODO later, use a separate user config? (github_gdpr) -from my.config import github as user_config - - -@dataclass -class github(user_config): - gdpr_dir: PathIsh # path to unpacked GDPR archive - - -config = make_config(github) +from my.core import Paths, Res, Stats, get_files, make_logger, stat, warnings +from my.core.error import echain +from .common import Event, EventIds, parse_dt logger = make_logger(__name__) +class config: + @property + @abstractmethod + def gdpr_dir(self) -> Paths: + raise NotImplementedError + + +def make_config() -> config: + # TODO later, use a separate user config? (github_gdpr) + from my.config import github as user_config + + class combined_config(user_config, config): + pass + + return combined_config() + + def inputs() -> Sequence[Path]: - gdir = config.gdpr_dir - res = get_files(gdir) + gdpr_dir = make_config().gdpr_dir + res = get_files(gdpr_dir) schema_json = [f for f in res if f.name == 'schema.json'] was_unpacked = len(schema_json) > 0 if was_unpacked: @@ -43,22 +49,37 @@ def inputs() -> Sequence[Path]: return res -def events() -> Iterable[Res[Event]]: +def events() -> Iterator[Res[Event]]: last = max(inputs()) logger.info(f'extracting data from {last}') - # a bit naughty and ad-hoc, but we will generify reading from tar.gz. once we have more examples - # another one is zulip archive - if last.is_dir(): - files = sorted(last.glob('*.json')) # looks like all files are in the root - open_file = lambda f: f.open() + root: Path | None = None + + if last.is_dir(): # if it's already CPath, this will match it + root = last else: - # treat as .tar.gz - tfile = tarfile.open(last) - files = sorted(map(Path, tfile.getnames())) - files = [p for p in files if len(p.parts) == 1 and p.suffix == '.json'] - open_file = lambda p: notnone(tfile.extractfile(f'./{p}')) # NOTE odd, doesn't work without ./ + try: + from kompress import CPath + + root = CPath(last) + assert len(list(root.iterdir())) > 0 # trigger to check if we have the kompress version with targz support + except Exception as e: + logger.exception(e) + warnings.high("Upgrade 'kompress' to latest version with native .tar.gz support. Falling back to unpacking to tmp dir.") + + if root is None: + from my.core.structure import match_structure + + with match_structure(last, expected=()) as res: # expected=() matches it regardless any patterns + [root] = res + yield from _process_one(root) + else: + yield from _process_one(root) + + +def _process_one(root: Path) -> Iterator[Res[Event]]: + files = sorted(root.glob('*.json')) # looks like all files are in the root # fmt: off handler_map = { @@ -100,8 +121,7 @@ def events() -> Iterable[Res[Event]]: # ignored continue - with open_file(f) as fo: - j = json.load(fo) + j = json.loads(f.read_text()) for r in j: try: yield handler(r) @@ -116,7 +136,7 @@ def stats() -> Stats: # TODO typing.TypedDict could be handy here.. -def _parse_common(d: Dict) -> Dict: +def _parse_common(d: dict) -> dict: url = d['url'] body = d.get('body') return { @@ -126,7 +146,7 @@ def _parse_common(d: Dict) -> Dict: } -def _parse_repository(d: Dict) -> Event: +def _parse_repository(d: dict) -> Event: pref = 'https://github.com/' url = d['url'] dts = d['created_at'] @@ -142,13 +162,13 @@ def _parse_repository(d: Dict) -> Event: # user may be None if the user was deleted -def _is_bot(user: Optional[str]) -> bool: +def _is_bot(user: str | None) -> bool: if user is None: return False return "[bot]" in user -def _parse_issue_comment(d: Dict) -> Event: +def _parse_issue_comment(d: dict) -> Event: url = d['url'] return Event( **_parse_common(d), @@ -158,7 +178,7 @@ def _parse_issue_comment(d: Dict) -> Event: ) -def _parse_issue(d: Dict) -> Event: +def _parse_issue(d: dict) -> Event: url = d['url'] title = d['title'] return Event( @@ -169,7 +189,7 @@ def _parse_issue(d: Dict) -> Event: ) -def _parse_pull_request(d: Dict) -> Event: +def _parse_pull_request(d: dict) -> Event: dts = d['created_at'] url = d['url'] title = d['title'] @@ -183,7 +203,7 @@ def _parse_pull_request(d: Dict) -> Event: ) -def _parse_project(d: Dict) -> Event: +def _parse_project(d: dict) -> Event: url = d['url'] title = d['name'] is_bot = "[bot]" in d["creator"] @@ -198,7 +218,7 @@ def _parse_project(d: Dict) -> Event: ) -def _parse_release(d: Dict) -> Event: +def _parse_release(d: dict) -> Event: tag = d['tag_name'] return Event( **_parse_common(d), @@ -207,7 +227,7 @@ def _parse_release(d: Dict) -> Event: ) -def _parse_commit_comment(d: Dict) -> Event: +def _parse_commit_comment(d: dict) -> Event: url = d['url'] return Event( **_parse_common(d), diff --git a/my/zulip/organization.py b/my/zulip/organization.py index 8725411..2e0df4b 100644 --- a/my/zulip/organization.py +++ b/my/zulip/organization.py @@ -1,38 +1,55 @@ """ Zulip data from [[https://memex.zulipchat.com/help/export-your-organization][Organization export]] """ + +from __future__ import annotations + +import json +from abc import abstractmethod from dataclasses import dataclass from datetime import datetime, timezone from itertools import count -import json from pathlib import Path -from typing import Sequence, Iterator, Dict, Union +from typing import Iterator, Sequence from my.core import ( - assert_never, - datetime_aware, - get_files, - stat, Json, Paths, Res, Stats, + assert_never, + datetime_aware, + get_files, + make_logger, + stat, + warnings, ) -from my.core.error import notnone -import my.config + +logger = make_logger(__name__) -@dataclass -class organization(my.config.zulip.organization): - # paths[s]/glob to the exported JSON data - export_path: Paths +class config: + @property + @abstractmethod + def export_path(self) -> Paths: + """paths[s]/glob to the exported JSON data""" + raise NotImplementedError + + +def make_config() -> config: + from my.config import zulip as user_config + + class combined_config(user_config.organization, config): + pass + + return combined_config() def inputs() -> Sequence[Path]: # TODO: seems like export ids are kinda random.. # not sure what's the best way to figure out the last without renaming? # could use mtime perhaps? - return get_files(organization.export_path, sort=False) + return get_files(make_config().export_path, sort=False) @dataclass(frozen=True) @@ -85,19 +102,39 @@ class Message: # todo cache it -def _entities() -> Iterator[Res[Union[Server, Sender, _Message]]]: +def _entities() -> Iterator[Res[Server | Sender | _Message]]: last = max(inputs()) - # todo would be nice to switch it to unpacked dirs as well, similar to ZipPath - # I guess makes sense to have a special implementation for .tar.gz considering how common are they - import tarfile + logger.info(f'extracting data from {last}') - tfile = tarfile.open(last) + root: Path | None = None - subdir = tfile.getnames()[0] # there is a directory inside tar file, first name should be that + if last.is_dir(): # if it's already CPath, this will match it + root = last + else: + try: + from kompress import CPath - with notnone(tfile.extractfile(f'{subdir}/realm.json')) as fo: - rj = json.load(fo) + root = CPath(last) + assert len(list(root.iterdir())) > 0 # trigger to check if we have the kompress version with targz support + except Exception as e: + logger.exception(e) + warnings.high("Upgrade 'kompress' to latest version with native .tar.gz support. Falling back to unpacking to tmp dir.") + + if root is None: + from my.core.structure import match_structure + + with match_structure(last, expected=()) as res: # expected=() matches it regardless any patterns + [root] = res + yield from _process_one(root) + else: + yield from _process_one(root) + + +def _process_one(root: Path) -> Iterator[Res[Server | Sender | _Message]]: + [subdir] = root.iterdir() # there is a directory inside tar file, first name should be that + + rj = json.loads((subdir / 'realm.json').read_text()) [sj] = rj['zerver_realm'] server = Server( @@ -136,12 +173,10 @@ def _entities() -> Iterator[Res[Union[Server, Sender, _Message]]]: for idx in count(start=1, step=1): fname = f'messages-{idx:06}.json' - fpath = f'{subdir}/{fname}' - if fpath not in tfile.getnames(): - # tarfile doesn't have .exists? + fpath = subdir / fname + if not fpath.exists(): break - with notnone(tfile.extractfile(fpath)) as fo: - mj = json.load(fo) + mj = json.loads(fpath.read_text()) # TODO handle zerver_usermessage for j in mj['zerver_message']: try: @@ -151,8 +186,8 @@ def _entities() -> Iterator[Res[Union[Server, Sender, _Message]]]: def messages() -> Iterator[Res[Message]]: - id2sender: Dict[int, Sender] = {} - id2server: Dict[int, Server] = {} + id2sender: dict[int, Sender] = {} + id2server: dict[int, Server] = {} for x in _entities(): if isinstance(x, Exception): yield x diff --git a/setup.py b/setup.py index cf4b79f..8335851 100644 --- a/setup.py +++ b/setup.py @@ -4,13 +4,13 @@ from setuptools import setup, find_namespace_packages # type: ignore INSTALL_REQUIRES = [ - 'pytz', # even though it's not needed by the core, it's so common anyway... - 'typing-extensions', # one of the most common pypi packages, ok to depend for core - 'appdirs', # very common, and makes it portable - 'more-itertools', # it's just too useful and very common anyway - 'decorator' , # less pain in writing correct decorators. very mature and stable, so worth keeping in core - 'click>=8.1' , # for the CLI, printing colors, decorator-based - may allow extensions to CLI - 'kompress' , # for transparent access to compressed files via pathlib.Path + 'pytz' , # even though it's not needed by the core, it's so common anyway... + 'typing-extensions' , # one of the most common pypi packages, ok to depend for core + 'appdirs' , # very common, and makes it portable + 'more-itertools' , # it's just too useful and very common anyway + 'decorator' , # less pain in writing correct decorators. very mature and stable, so worth keeping in core + 'click>=8.1' , # for the CLI, printing colors, decorator-based - may allow extensions to CLI + 'kompress>=0.2.20240918' , # for transparent access to compressed files via pathlib.Path ] From 2ca323da8487a2f99d283bd78c8141a35b700cb3 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 21 Sep 2024 23:18:50 +0100 Subject: [PATCH 34/55] my.fbmessenger.android: exclude unsent messages to avoid duplication --- my/fbmessenger/android.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index 7e48c78..effabab 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -168,6 +168,15 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: CAST(sender_id AS TEXT) AS sender_id, reply_source_id FROM messages + WHERE + /* Regular message_id conforms to mid.* regex. + However seems that when message is not sent yet it doesn't have this server id yet + (happened only once, but could be just luck of course!) + We exclude these messages to avoid duplication. + However poisitive filter (e.g. message_id LIKE 'mid%') feels a bit wrong, e.g. what if mesage ids change or something + So instead this excludes only such unsent messages. + */ + message_id != offline_threading_id ORDER BY timestamp_ms /* they aren't in order in the database, so need to sort */ ''' ): From e036cc9e8523debe92829ec7dc7b3b867860535f Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 21 Sep 2024 23:55:06 +0100 Subject: [PATCH 35/55] my.twitter.android: get own user id as string, consistent with rest of module --- my/twitter/android.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index 7adfeb6..ada04ae 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -156,10 +156,11 @@ def get_own_user_id(conn) -> str: # unclear what's the reliable way to query it, so we use multiple different ones and arbitrate # NOTE: 'SELECT DISTINCT ev_owner_id FROM lists' doesn't work, might include lists from other people? res: Set[str] = set() + # need to cast as it's int by default for q in [ - 'SELECT DISTINCT list_mapping_user_id FROM list_mapping', - 'SELECT DISTINCT owner_id FROM cursors', - 'SELECT DISTINCT user_id FROM users WHERE _id == 1', + 'SELECT DISTINCT CAST(list_mapping_user_id AS TEXT) FROM list_mapping', + 'SELECT DISTINCT CAST(owner_id AS TEXT) FROM cursors', + 'SELECT DISTINCT CAST(user_id AS TEXT) FROM users WHERE _id == 1', ]: for (r,) in conn.execute(q): res.add(r) From 239e6617fe62f7b14e71092175148255a10f4ac9 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 01:48:12 +0100 Subject: [PATCH 36/55] my.twitter.archive: deduplicate tweets based on id_str/created_at and raw tweet text --- my/twitter/archive.py | 73 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/my/twitter/archive.py b/my/twitter/archive.py index d326d70..5fa89f4 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -226,11 +226,80 @@ class ZipExport: yield Like(r, screen_name=self.screen_name) +def _cleanup_tweet_json(rj: Json) -> None: + # note: for now this isn't used, was just an attempt to normalise raw data... + + rj.pop('edit_info', None) # useless for downstream processing, but results in dupes, so let's remove it + + ## could probably just take the last one? dunno + rj.pop('retweet_count', None) + rj.pop('favorite_count', None) + ## + + entities = rj.get('entities', {}) + ext_entities = rj.get('extended_entities', {}) + + # TODO shit. unclear how to 'merge' changes to these + # links sometimes change for no apparent reason -- and sometimes old one is still valid but not the new one??? + for m in entities.get('media', {}): + m.pop('media_url', None) + m.pop('media_url_https', None) + for m in ext_entities.get('media', {}): + m.pop('media_url', None) + m.pop('media_url_https', None) + ## + + for m in entities.get('user_mentions', {}): + # changes if user renames themselves... + m.pop('name', None) + + # hmm so can change to -1? maybe if user was deleted? + # but also can change to actually something else?? second example + entities.pop('user_mentions', None) + + # TODO figure out what else is changing there later... + rj.pop('entities', None) + rj.pop('extended_entities', None) + + ## useless attributes which should be fine to exclude + rj.pop('possibly_sensitive', None) # not sure what is this.. sometimes appears with False value?? + rj.pop('withheld_in_countries', None) + rj.pop('lang', None) + ## + + # ugh. might change if the Twitter client was deleted or description renamed?? + rj.pop('source', None) + + ## ugh. sometimes trailing 0 after decimal point is present? + rj.pop('coordinates', None) + rj.get('geo', {}).pop('coordinates', None) + ## + + # ugh. this changes if user changed their name... + # or disappears if account was deleted? + rj.pop('in_reply_to_screen_name', None) + + # todo not sure about list and sorting? although can't hurt considering json is not iterative? def tweets() -> Iterator[Res[Tweet]]: _all = chain.from_iterable(ZipExport(i).tweets() for i in inputs()) - res = unique_everseen(_all, key=json_dumps) - yield from sorted(res, key=lambda t: t.dt) + + # NOTE raw json data in archived tweets changes all the time even for same tweets + # there is an attempt to clean it up... but it's tricky since users rename themselves, twitter stats are changing + # so it's unclear how to pick up + # we should probably 'merge' tweets into a canonical version, e.g. + # - pick latest tweet stats + # - keep history of usernames we were replying to that share the same user id + # - pick 'best' media url somehow?? + # - normalise coordinates data + def key(t: Tweet): + # NOTE: not using t.text, since it actually changes if entities in tweet are changing... + # whereas full_text seems stable + text = t.raw['full_text'] + return (t.created_at, t.id_str, text) + + res = unique_everseen(_all, key=key) + yield from sorted(res, key=lambda t: t.created_at) def likes() -> Iterator[Res[Like]]: From 02dabe9f2b90a472fc878aa31ee7299e094b137d Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 02:03:28 +0100 Subject: [PATCH 37/55] my.twitter.archive: cleanup linting and use proper configuration via abstract class --- my/twitter/archive.py | 97 ++++++++++++++++++++++--------------------- 1 file changed, 50 insertions(+), 47 deletions(-) diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 5fa89f4..1573754 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -2,73 +2,75 @@ Twitter data (uses [[https://help.twitter.com/en/managing-your-account/how-to-download-your-twitter-archive][official twitter archive export]]) """ +from __future__ import annotations -# before this config was named 'twitter', doesn't make too much sense for archive -# todo unify with other code like this, e.g. time.tz.via_location -try: - from my.config import twitter_archive as user_config -except ImportError as ie: - if not (ie.name == 'my.config' and 'twitter_archive' in str(ie)): - # must be caused by something else - raise ie - try: - from my.config import twitter as user_config # type: ignore[assignment] - except ImportError: - raise ie # raise the original exception.. must be something else # noqa: B904 - else: - from my.core import warnings - warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') -## - - +import html +import json # hmm interesting enough, orjson didn't give much speedup here? +from abc import abstractmethod from dataclasses import dataclass from datetime import datetime -from itertools import chain -import json # hmm interesting enough, orjson didn't give much speedup here? -from pathlib import Path from functools import cached_property -import html +from itertools import chain +from pathlib import Path from typing import ( + TYPE_CHECKING, Iterator, - List, - Optional, Sequence, ) from more_itertools import unique_everseen from my.core import ( - datetime_aware, - get_files, - make_logger, - stat, Json, Paths, Res, Stats, + datetime_aware, + get_files, + make_logger, + stat, + warnings, ) -from my.core import warnings -from my.core.cfg import make_config from my.core.serialize import dumps as json_dumps from .common import TweetId, permalink - -@dataclass -class twitter_archive(user_config): - export_path: Paths # path[s]/glob to the twitter archive takeout - - -### - -config = make_config(twitter_archive) - - logger = make_logger(__name__) +class config: + @property + @abstractmethod + def export_path(self) -> Paths: + """path[s]/glob to the twitter archive takeout""" + raise NotImplementedError + + +def make_config() -> config: + # before this config was named 'twitter', doesn't make too much sense for archive + # todo unify with other code like this, e.g. time.tz.via_location + try: + from my.config import twitter_archive as user_config + except ImportError as ie: + if not (ie.name == 'my.config' and 'twitter_archive' in str(ie)): + # must be caused by something else + raise ie + try: + from my.config import twitter as user_config # type: ignore[assignment] + except ImportError: + raise ie # raise the original exception.. must be something else # noqa: B904 + else: + warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') + ## + + class combined_config(user_config, config): + pass + + return combined_config() + + def inputs() -> Sequence[Path]: - return get_files(config.export_path) + return get_files(make_config().export_path) # TODO make sure it's not used anywhere else and simplify interface @@ -121,7 +123,7 @@ class Tweet: return res @property - def urls(self) -> List[str]: + def urls(self) -> list[str]: ents = self.entities us = ents['urls'] return [u['expanded_url'] for u in us] @@ -162,10 +164,10 @@ class Like: return self.raw['tweetId'] @property - def text(self) -> Optional[str]: + def text(self) -> str | None: # NOTE: likes basically don't have anything except text and url # ugh. I think none means that tweet was deleted? - res: Optional[str] = self.raw.get('fullText') + res: str | None = self.raw.get('fullText') if res is None: return None res = html.unescape(res) @@ -186,7 +188,7 @@ class ZipExport: if not (self.zpath / 'Your archive.html').exists(): self.old_format = True - def raw(self, what: str, *, fname: Optional[str] = None) -> Iterator[Json]: + def raw(self, what: str, *, fname: str | None = None) -> Iterator[Json]: logger.info(f'{self.zpath} : processing {what}') path = fname or what @@ -317,4 +319,5 @@ def stats() -> Stats: ## Deprecated stuff -Tid = TweetId +if not TYPE_CHECKING: + Tid = TweetId From 3166109f15c08f8a23e60a384047b7f9125c252b Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 04:27:32 +0100 Subject: [PATCH 38/55] my.core: fix list constructor in always_support_sequence and add some tests --- my/core/hpi_compat.py | 132 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 121 insertions(+), 11 deletions(-) diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 6261c23..949046d 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -2,6 +2,7 @@ Contains various backwards compatibility/deprecation helpers relevant to HPI itself. (as opposed to .compat module which implements compatibility between python versions) """ + import inspect import os import re @@ -116,32 +117,141 @@ V = TypeVar('V') # named to be kinda consistent with more_itertools, e.g. more_itertools.always_iterable class always_supports_sequence(Iterator[V]): """ - Helper to make migration from Sequence/List to Iterable/Iterator type backwards compatible + Helper to make migration from Sequence/List to Iterable/Iterator type backwards compatible in runtime """ def __init__(self, it: Iterator[V]) -> None: - self.it = it - self._list: Optional[List] = None + self._it = it + self._list: Optional[List[V]] = None + self._lit: Optional[Iterator[V]] = None def __iter__(self) -> Iterator[V]: # noqa: PYI034 - return self.it.__iter__() + if self._list is not None: + self._lit = iter(self._list) + return self def __next__(self) -> V: - return self.it.__next__() + if self._list is not None: + assert self._lit is not None + delegate = self._lit + else: + delegate = self._it + return next(delegate) def __getattr__(self, name): - return getattr(self.it, name) + return getattr(self._it, name) @property - def aslist(self) -> List[V]: + def _aslist(self) -> List[V]: if self._list is None: - qualname = getattr(self.it, '__qualname__', '') # defensive just in case + qualname = getattr(self._it, '__qualname__', '') # defensive just in case warnings.medium(f'Using {qualname} as list is deprecated. Migrate to iterative processing or call list() explicitly.') - self._list = list(self.it) + self._list = list(self._it) + + # this is necessary for list constructor to work correctly + # since it's __iter__ first, then tries to compute length and then starts iterating... + self._lit = iter(self._list) return self._list def __len__(self) -> int: - return len(self.aslist) + return len(self._aslist) def __getitem__(self, i: int) -> V: - return self.aslist[i] + return self._aslist[i] + + +def test_always_supports_sequence_list_constructor() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + # list constructor is a bit special... it's trying to compute length if it's available to optimize memory allocation + # so, what's happening in this case is + # - sit.__iter__ is called + # - sit.__len__ is called + # - sit.__next__ is called + res = list(sit) + assert res == ['a', 'b', 'c'] + assert exhausted == 1 + + res = list(sit) + assert res == ['a', 'b', 'c'] + assert exhausted == 1 # this will iterate over 'cached' list now, so original generator is only exhausted once + + +def test_always_supports_sequence_indexing() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + assert len(sit) == 3 + assert exhausted == 1 + + assert sit[2] == 'c' + assert sit[1] == 'b' + assert sit[0] == 'a' + assert exhausted == 1 + + # a few tests to make sure list-like operations are working.. + assert list(sit) == ['a', 'b', 'c'] + assert [x for x in sit] == ['a', 'b', 'c'] # noqa: C416 + assert list(sit) == ['a', 'b', 'c'] + assert [x for x in sit] == ['a', 'b', 'c'] # noqa: C416 + assert exhausted == 1 + + +def test_always_supports_sequence_next() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + x = next(sit) + assert x == 'a' + assert exhausted == 0 + + x = next(sit) + assert x == 'b' + assert exhausted == 0 + + +def test_always_supports_sequence_iter() -> None: + exhausted = 0 + + def it() -> Iterator[str]: + nonlocal exhausted + yield from ['a', 'b', 'c'] + exhausted += 1 + + sit = always_supports_sequence(it()) + + for x in sit: + assert x == 'a' + break + + x = next(sit) + assert x == 'b' + + assert exhausted == 0 + + x = next(sit) + assert x == 'c' + assert exhausted == 0 + + for _ in sit: + raise RuntimeError # shouldn't trigger, just exhaust the iterator + assert exhausted == 1 From 75639a3d5ec3b07fb7e6b638e9e3c342a23cc1a2 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 19:50:58 +0100 Subject: [PATCH 39/55] tox: some prep for potentially using uv on CI instead of pip see https://github.com/karlicoss/HPI/issues/391 --- setup.py | 10 ++++++++ tox.ini | 78 +++++++++++++++++++++++++++++--------------------------- 2 files changed, 51 insertions(+), 37 deletions(-) diff --git a/setup.py b/setup.py index 8335851..e49eee0 100644 --- a/setup.py +++ b/setup.py @@ -58,6 +58,16 @@ def main() -> None: 'orjson', # for my.core.serialize and denylist 'simplejson', # for my.core.serialize + + ## + # ideally we'd use --instal-types in mypy + # , but looks like it doesn't respect uv venv if it's running in it :( + 'types-pytz' , # for my.core + 'types-decorator' , # for my.core.compat + 'pandas-stubs' , # for my.core.pandas + 'types-dateparser', # for my.core.query_range + 'types-simplejson', # for my.core.serialize + ## ], 'optional': [ # todo document these? diff --git a/tox.ini b/tox.ini index 6b95088..4e5dff6 100644 --- a/tox.ini +++ b/tox.ini @@ -24,16 +24,19 @@ passenv = [testenv:ruff] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing] commands = - {envpython} -m pip install --use-pep517 -e .[testing] {envpython} -m ruff check my/ # just the very core tests with minimal dependencies [testenv:tests-core] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing] commands = - {envpython} -m pip install --use-pep517 -e .[testing] - {envpython} -m pytest \ # importlib is the new suggested import-mode # without it test package names end up as core.tests.* instead of my.core.tests.* @@ -53,31 +56,26 @@ setenv = # TODO not sure if need it? MY_CONFIG=nonexistent HPI_TESTS_USES_OPTIONAL_DEPS=true +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing] + cachew + ijson # optional dependency for various modules commands = - {envpython} -m pip install --use-pep517 -e .[testing] - - {envpython} -m pip install cachew - - {envpython} -m my.core module install my.location.google - {envpython} -m pip install ijson # optional dependency - - # tz/location - {envpython} -m my.core module install my.time.tz.via_location - {envpython} -m my.core module install my.ip.all - {envpython} -m my.core module install my.location.gpslogger - {envpython} -m my.core module install my.location.fallback.via_ip - {envpython} -m my.core module install my.google.takeout.parser - - {envpython} -m my.core module install my.calendar.holidays - - # my.body.weight dep - {envpython} -m my.core module install my.orgmode - - {envpython} -m my.core module install my.coding.commits - - {envpython} -m my.core module install my.pdfs - - {envpython} -m my.core module install my.reddit.rexport + {envpython} -m my.core module install \ + ## tz/location + my.location.google \ + my.time.tz.via_location \ + my.ip.all \ + my.location.gpslogger \ + my.location.fallback.via_ip \ + my.google.takeout.parser \ + ## + my.calendar.holidays \ + my.orgmode \ # my.body.weight dep + my.coding.commits \ + my.pdfs \ + my.reddit.rexport {envpython} -m pytest \ # importlib is the new suggested import-mode @@ -88,18 +86,20 @@ commands = [testenv:demo] +deps = + git+https://github.com/karlicoss/hypexport commands = - {envpython} -m pip install git+https://github.com/karlicoss/hypexport {envpython} ./demo.py [testenv:mypy-core] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing,optional] + orgparse # for core.orgmode + gpxpy # for hpi query --output gpx commands = - {envpython} -m pip install --use-pep517 -e .[testing,optional] - {envpython} -m pip install orgparse # used it core.orgmode? - {envpython} -m pip install gpxpy # for hpi query --output gpx - - {envpython} -m mypy --install-types --non-interactive \ + {envpython} -m mypy --no-install-types \ -p {[testenv]package_name}.core \ --txt-report .coverage.mypy-core \ --html-report .coverage.mypy-core \ @@ -109,9 +109,13 @@ commands = # specific modules that are known to be mypy compliant (to avoid false negatives) # todo maybe split into separate jobs? need to add comment how to run [testenv:mypy-misc] +install_command = {envpython} -m pip install --use-pep517 {opts} {packages} +deps = + -e .[testing,optional] + lxml-stubs # for my.smscalls + types-protobuf # for my.google.maps.android + types-Pillow # for my.photos commands = - {envpython} -m pip install --use-pep517 -e .[testing,optional] - {envpython} -m my.core module install \ my.arbtt \ my.browser.export \ @@ -143,13 +147,13 @@ commands = my.time.tz.via_location - {envpython} -m mypy --install-types --non-interactive \ + {envpython} -m mypy --no-install-types \ -p {[testenv]package_name} \ --txt-report .coverage.mypy-misc \ --html-report .coverage.mypy-misc \ {posargs} - {envpython} -m mypy --install-types --non-interactive \ + {envpython} -m mypy --no-install-types \ tests # note: this comment doesn't seem relevant anymore, but keeping it in case the issue happens again From 8ed9e1947ec186b7939e2d8a53d07b6ffdd832ed Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 17:47:05 +0100 Subject: [PATCH 40/55] my.youtube.takeout: deduplicate watched videos and sort out a few minor errors --- my/core/compat.py | 7 ++- my/media/youtube.py | 13 +++-- my/youtube/takeout.py | 115 ++++++++++++++++++++++++++++++++---------- 3 files changed, 102 insertions(+), 33 deletions(-) diff --git a/my/core/compat.py b/my/core/compat.py index eccaf07..29d4f04 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -22,12 +22,17 @@ if not TYPE_CHECKING: source.backup(dest, **kwargs) -# can remove after python3.9 (although need to keep the method itself for bwd compat) +## can remove after python3.9 (although need to keep the method itself for bwd compat) def removeprefix(text: str, prefix: str) -> str: if text.startswith(prefix): return text[len(prefix) :] return text +def removesuffix(text: str, suffix: str) -> str: + if text.endswith(suffix): + return text[:-len(suffix)] + return text +## ## used to have compat function before 3.8 for these, keeping for runtime back compatibility if not TYPE_CHECKING: diff --git a/my/media/youtube.py b/my/media/youtube.py index efaa74b..3ddbc14 100644 --- a/my/media/youtube.py +++ b/my/media/youtube.py @@ -1,5 +1,10 @@ -from ..core.warnings import high -high("DEPRECATED! Please use my.youtube.takeout instead.") -from ..core.util import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ -from ..youtube.takeout import * +from typing import TYPE_CHECKING + +from my.core.warnings import high + +high("DEPRECATED! Please use my.youtube.takeout instead.") + +if not TYPE_CHECKING: + from my.youtube.takeout import * diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 284c082..bbce46a 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -1,13 +1,16 @@ -from typing import NamedTuple, List, Iterable, TYPE_CHECKING +from __future__ import annotations -from my.core import datetime_aware, make_logger, stat, Res, Stats -from my.core.compat import deprecated, removeprefix +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Iterable, Iterator +from my.core import Res, Stats, datetime_aware, make_logger, stat, warnings +from my.core.compat import deprecated, removeprefix, removesuffix logger = make_logger(__name__) -class Watched(NamedTuple): +@dataclass +class Watched: url: str title: str when: datetime_aware @@ -16,19 +19,57 @@ class Watched(NamedTuple): def eid(self) -> str: return f'{self.url}-{self.when.isoformat()}' + def is_deleted(self) -> bool: + return self.title == self.url + # todo define error policy? # although it has one from google takeout module.. so not sure -def watched() -> Iterable[Res[Watched]]: + +def watched() -> Iterator[Res[Watched]]: + emitted: dict[Any, Watched] = {} + for w in _watched(): + if isinstance(w, Exception): + yield w # TODO also make unique? + continue + + # older exports (e.g. html) didn't have microseconds + # wheras newer json ones do have them + # seconds resolution is enough to distinguish watched videos + # also we're processing takeouts in HPI in reverse order, so first seen watch would contain microseconds, resulting in better data + without_microsecond = w.when.replace(microsecond=0) + + key = w.url, without_microsecond + prev = emitted.get(key, None) + if prev is not None: + # NOTE: some video titles start with 'Liked ' for liked videos activity + # but they'd have different timestamp, so fine not to handle them as a special case here + if w.title in prev.title: + # often more stuff added to the title, like 'Official Video' + # in this case not worth emitting the change + # also handles the case when titles match + continue + # otherwise if title changed completely, just emit the change... not sure what else we could do? + # could merge titles in the 'titles' field and update dynamically? but a bit complicated, maybe later.. + + # TODO would also be nice to handle is_deleted here somehow... + # but for that would need to process data in direct order vs reversed.. + # not sure, maybe this could use a special mode or something? + + emitted[key] = w + yield w + + +def _watched() -> Iterator[Res[Watched]]: try: - from ..google.takeout.parser import events from google_takeout_parser.models import Activity + + from ..google.takeout.parser import events except ModuleNotFoundError as ex: logger.exception(ex) - from ..core.warnings import high - high("Please set up my.google.takeout.parser module for better youtube support. Falling back to legacy implementation.") - yield from _watched_legacy() + warnings.high("Please set up my.google.takeout.parser module for better youtube support. Falling back to legacy implementation.") + yield from _watched_legacy() # type: ignore[name-defined] return YOUTUBE_VIDEO_LINK = '://www.youtube.com/watch?v=' @@ -43,12 +84,12 @@ def watched() -> Iterable[Res[Watched]]: continue url = e.titleUrl - header = e.header - title = e.title if url is None: continue + header = e.header + if header in {'Image Search', 'Search', 'Chrome'}: # sometimes results in youtube links.. but definitely not watch history continue @@ -61,6 +102,8 @@ def watched() -> Iterable[Res[Watched]]: pass continue + title = e.title + if header == 'youtube.com' and title.startswith('Visited '): continue @@ -76,16 +119,32 @@ def watched() -> Iterable[Res[Watched]]: # also compatible with legacy titles title = removeprefix(title, 'Watched ') + # watches originating from some activity end with this, remove it for consistency + title = removesuffix(title, ' - YouTube') + if YOUTUBE_VIDEO_LINK not in url: - if e.details == ['From Google Ads']: - # weird, sometimes results in odd + if 'youtube.com/post/' in url: + # some sort of channel updates? continue - if title == 'Used YouTube' and e.products == ['Android']: + if 'youtube.com/playlist' in url: + # 'saved playlist' actions + continue + if 'music.youtube.com' in url: + # todo maybe allow it? + continue + if any('From Google Ads' in d for d in e.details): + # weird, sometimes results in odd urls + continue + + if title == 'Used YouTube': continue yield RuntimeError(f'Unexpected url: {e}') continue + # TODO contribute to takeout parser? seems that these still might happen in json data + title = title.replace("\xa0", " ") + yield Watched( url=url, title=title, @@ -100,24 +159,24 @@ def stats() -> Stats: ### deprecated stuff (keep in my.media.youtube) if not TYPE_CHECKING: + @deprecated("use 'watched' instead") def get_watched(*args, **kwargs): return watched(*args, **kwargs) + def _watched_legacy() -> Iterable[Watched]: + from ..google.takeout.html import read_html + from ..google.takeout.paths import get_last_takeout -def _watched_legacy() -> Iterable[Watched]: - from ..google.takeout.html import read_html - from ..google.takeout.paths import get_last_takeout + # todo looks like this one doesn't have retention? so enough to use the last + path = 'Takeout/My Activity/YouTube/MyActivity.html' + last = get_last_takeout(path=path) + if last is None: + return [] - # todo looks like this one doesn't have retention? so enough to use the last - path = 'Takeout/My Activity/YouTube/MyActivity.html' - last = get_last_takeout(path=path) - if last is None: - return [] + watches: list[Watched] = [] + for dt, url, title in read_html(last, path): + watches.append(Watched(url=url, title=title, when=dt)) - watches: List[Watched] = [] - for dt, url, title in read_html(last, path): - watches.append(Watched(url=url, title=title, when=dt)) - - # todo hmm they already come sorted.. wonder if should just rely on it.. - return sorted(watches, key=lambda e: e.when) + # todo hmm they already come sorted.. wonder if should just rely on it.. + return sorted(watches, key=lambda e: e.when) From bf8af6c598803b7ad3bee5d5cbade015ce4b88a7 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 22 Sep 2024 22:32:34 +0100 Subject: [PATCH 41/55] tox: try using uv for CI, should result in speedup see https://github.com/karlicoss/HPI/issues/391 --- .ci/run | 13 ++++++++++--- my/core/__main__.py | 3 ++- tox.ini | 10 +++++----- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.ci/run b/.ci/run index fe2719e..7656575 100755 --- a/.ci/run +++ b/.ci/run @@ -11,6 +11,8 @@ if ! command -v sudo; then } fi +# --parallel-live to show outputs while it's running +tox_cmd='run-parallel --parallel-live' if [ -n "${CI-}" ]; then # install OS specific stuff here case "$OSTYPE" in @@ -20,7 +22,8 @@ if [ -n "${CI-}" ]; then ;; cygwin* | msys* | win*) # windows - : + # ugh. parallel stuff seems super flaky under windows, some random failures, "file used by other process" and crap like that + tox_cmd='run' ;; *) # must be linux? @@ -37,5 +40,9 @@ if ! command -v python3 &> /dev/null; then PY_BIN="python" fi -"$PY_BIN" -m pip install --user tox -"$PY_BIN" -m tox --parallel --parallel-live "$@" + +# TODO hmm for some reason installing uv with pip and then running +# "$PY_BIN" -m uv tool fails with missing setuptools error?? +# just uvx directly works, but it's not present in PATH... +"$PY_BIN" -m pip install --user pipx +"$PY_BIN" -m pipx run uv tool run --with=tox-uv tox $tox_cmd "$@" diff --git a/my/core/__main__.py b/my/core/__main__.py index c675676..9ec637c 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -373,8 +373,9 @@ def module_install(*, user: bool, module: Sequence[str], parallel: bool=False, b warning('requirements list is empty, no need to install anything') return + use_uv = 'HPI_MODULE_INSTALL_USE_UV' in os.environ pre_cmd = [ - sys.executable, '-m', 'pip', + sys.executable, '-m', *(['uv'] if use_uv else []), 'pip', 'install', *(['--user'] if user else []), # todo maybe instead, forward all the remaining args to pip? *(['--break-system-packages'] if break_system_packages else []), # https://peps.python.org/pep-0668/ diff --git a/tox.ini b/tox.ini index 4e5dff6..d202bd2 100644 --- a/tox.ini +++ b/tox.ini @@ -17,6 +17,9 @@ passenv = PYTHONPYCACHEPREFIX MYPY_CACHE_DIR RUFF_CACHE_DIR +setenv = + HPI_MODULE_INSTALL_USE_UV=true +uv_seed = true # seems necessary so uv creates separate venvs per tox env? # note: --use-pep517 below is necessary for tox --parallel flag to work properly @@ -24,7 +27,6 @@ passenv = [testenv:ruff] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing] commands = @@ -33,7 +35,6 @@ commands = # just the very core tests with minimal dependencies [testenv:tests-core] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing] commands = @@ -56,9 +57,9 @@ setenv = # TODO not sure if need it? MY_CONFIG=nonexistent HPI_TESTS_USES_OPTIONAL_DEPS=true -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing] + uv # for hpi module install cachew ijson # optional dependency for various modules commands = @@ -93,7 +94,6 @@ commands = [testenv:mypy-core] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing,optional] orgparse # for core.orgmode @@ -109,9 +109,9 @@ commands = # specific modules that are known to be mypy compliant (to avoid false negatives) # todo maybe split into separate jobs? need to add comment how to run [testenv:mypy-misc] -install_command = {envpython} -m pip install --use-pep517 {opts} {packages} deps = -e .[testing,optional] + uv # for hpi module install lxml-stubs # for my.smscalls types-protobuf # for my.google.maps.android types-Pillow # for my.photos From 6a6d15704063c328f9bf66330630a53a0c421915 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 23 Sep 2024 01:14:49 +0100 Subject: [PATCH 42/55] cli: fix minor race condition in creating hpi_temp_dir --- my/core/__main__.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/my/core/__main__.py b/my/core/__main__.py index 9ec637c..a80aa52 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -615,9 +615,8 @@ def main(*, debug: bool) -> None: # to run things at the end (would need to use a callback or pass context) # https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts - tdir: str = os.path.join(tempfile.gettempdir(), 'hpi_temp_dir') - if not os.path.exists(tdir): - os.makedirs(tdir) + tdir = Path(tempfile.gettempdir()) / 'hpi_temp_dir' + tdir.mkdir(exist_ok=True) os.chdir(tdir) From a8f86e32b981aef62890605e12da9cd59c9cc0c8 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Mon, 23 Sep 2024 22:01:57 +0100 Subject: [PATCH 43/55] core.time: hotfix for default force_abbreviations attribute --- my/core/time.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/my/core/time.py b/my/core/time.py index 6de4105..fa20a7c 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -11,11 +11,11 @@ def user_forced() -> Sequence[str]: # https://stackoverflow.com/questions/36067621/python-all-possible-timezone-abbreviations-for-given-timezone-name-and-vise-ve try: from my.config import time as user_config + return user_config.tz.force_abbreviations # type: ignore[attr-defined] # noqa: TRY300 + # note: noqa since we're catching case where config doesn't have attribute here as well except: # todo log/apply policy return [] - else: - return user_config.tz.force_abbreviations # type: ignore[attr-defined] @lru_cache(1) From bc7c3ac25355899f2a4ae56382469d85fd2c33bc Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 19 Oct 2024 18:27:35 +0100 Subject: [PATCH 44/55] general: python3.9 reached EOL, switch min version also enable 3.13 on CI --- .github/workflows/main.yml | 11 ++++++---- my/core/__main__.py | 4 +--- my/core/_deprecated/kompress.py | 2 +- my/core/compat.py | 24 ++++++++------------- my/core/pandas.py | 2 +- my/core/utils/concurrent.py | 38 +++++++++++---------------------- my/youtube/takeout.py | 6 +++--- setup.py | 2 +- 8 files changed, 36 insertions(+), 53 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 53d8e53..111d0e9 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -21,19 +21,20 @@ on: jobs: build: strategy: + fail-fast: false matrix: platform: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.8', '3.9', '3.10', '3.11', '3.12'] + python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] exclude: [ # windows runners are pretty scarce, so let's only run lowest and highest python version - {platform: windows-latest, python-version: '3.9' }, {platform: windows-latest, python-version: '3.10'}, {platform: windows-latest, python-version: '3.11'}, + {platform: windows-latest, python-version: '3.12'}, # same, macos is a bit too slow and ubuntu covers python quirks well - {platform: macos-latest , python-version: '3.9' }, {platform: macos-latest , python-version: '3.10' }, {platform: macos-latest , python-version: '3.11' }, + {platform: macos-latest , python-version: '3.12' }, ] runs-on: ${{ matrix.platform }} @@ -63,11 +64,13 @@ jobs: - if: matrix.platform == 'ubuntu-latest' # no need to compute coverage for other platforms uses: actions/upload-artifact@v4 with: + include-hidden-files: true name: .coverage.mypy-misc_${{ matrix.platform }}_${{ matrix.python-version }} path: .coverage.mypy-misc/ - if: matrix.platform == 'ubuntu-latest' # no need to compute coverage for other platforms uses: actions/upload-artifact@v4 with: + include-hidden-files: true name: .coverage.mypy-core_${{ matrix.platform }}_${{ matrix.python-version }} path: .coverage.mypy-core/ @@ -81,7 +84,7 @@ jobs: - uses: actions/setup-python@v5 with: - python-version: '3.8' + python-version: '3.10' - uses: actions/checkout@v4 with: diff --git a/my/core/__main__.py b/my/core/__main__.py index a80aa52..2777008 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -171,8 +171,6 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module # use a temporary directory, useful because # - compileall ignores -B, so always craps with .pyc files (annoyng on RO filesystems) # - compileall isn't following symlinks, just silently ignores them - # note: ugh, annoying that copytree requires a non-existing dir before 3.8. - # once we have min version 3.8, can use dirs_exist_ok=True param tdir = Path(td) / 'cfg' # NOTE: compileall still returns code 0 if the path doesn't exist.. # but in our case hopefully it's not an issue @@ -181,7 +179,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module try: # this will resolve symlinks when copying # should be under try/catch since might fail if some symlinks are missing - shutil.copytree(cfg_path, tdir) + shutil.copytree(cfg_path, tdir, dirs_exist_ok=True) check_call(cmd) info('syntax check: ' + ' '.join(cmd)) except Exception as e: diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index b08f04b..cd27a7f 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -210,7 +210,7 @@ class ZipPath(zipfile_Path): def iterdir(self) -> Iterator[ZipPath]: for s in self._as_dir().iterdir(): - yield ZipPath(s.root, s.at) # type: ignore[attr-defined] + yield ZipPath(s.root, s.at) @property def stem(self) -> str: diff --git a/my/core/compat.py b/my/core/compat.py index 29d4f04..3273ff4 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -21,25 +21,19 @@ if not TYPE_CHECKING: # TODO warn here? source.backup(dest, **kwargs) + # keeping for runtime backwards compatibility (added in 3.9) + @deprecated('use .removeprefix method on string directly instead') + def removeprefix(text: str, prefix: str) -> str: + return text.removeprefix(prefix) -## can remove after python3.9 (although need to keep the method itself for bwd compat) -def removeprefix(text: str, prefix: str) -> str: - if text.startswith(prefix): - return text[len(prefix) :] - return text + @deprecated('use .removesuffix method on string directly instead') + def removesuffix(text: str, suffix: str) -> str: + return text.removesuffix(suffix) + ## -def removesuffix(text: str, suffix: str) -> str: - if text.endswith(suffix): - return text[:-len(suffix)] - return text -## - -## used to have compat function before 3.8 for these, keeping for runtime back compatibility -if not TYPE_CHECKING: + ## used to have compat function before 3.8 for these, keeping for runtime back compatibility from functools import cached_property from typing import Literal, Protocol, TypedDict -else: - from typing_extensions import Literal, Protocol, TypedDict ## diff --git a/my/core/pandas.py b/my/core/pandas.py index d38465a..8f5fd29 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -181,7 +181,7 @@ Schema = Any def _as_columns(s: Schema) -> Dict[str, Type]: # todo would be nice to extract properties; add tests for this as well if dataclasses.is_dataclass(s): - return {f.name: f.type for f in dataclasses.fields(s)} + return {f.name: f.type for f in dataclasses.fields(s)} # type: ignore[misc] # ugh, why mypy thinks f.type can return str?? # else must be NamedTuple?? # todo assert my.core.common.is_namedtuple? return getattr(s, '_field_types') diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 146861b..73944ec 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -1,6 +1,6 @@ import sys from concurrent.futures import Executor, Future -from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar +from typing import Any, Callable, Optional, TypeVar from ..compat import ParamSpec @@ -19,33 +19,21 @@ class DummyExecutor(Executor): self._shutdown = False self._max_workers = max_workers - if TYPE_CHECKING: - if sys.version_info[:2] <= (3, 8): - # 3.8 doesn't support ParamSpec as Callable arg :( - # and any attempt to type results in incompatible supertype.. so whatever - def submit(self, fn, *args, **kwargs): ... + def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: + if self._shutdown: + raise RuntimeError('cannot schedule new futures after shutdown') + f: Future[Any] = Future() + try: + result = fn(*args, **kwargs) + except KeyboardInterrupt: + raise + except BaseException as e: + f.set_exception(e) else: + f.set_result(result) - def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... - - else: - - def submit(self, fn, *args, **kwargs): - if self._shutdown: - raise RuntimeError('cannot schedule new futures after shutdown') - - f: Future[Any] = Future() - try: - result = fn(*args, **kwargs) - except KeyboardInterrupt: - raise - except BaseException as e: - f.set_exception(e) - else: - f.set_result(result) - - return f + return f def shutdown(self, wait: bool = True, **kwargs) -> None: # noqa: FBT001,FBT002,ARG002 self._shutdown = True diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index bbce46a..f29b2e3 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -4,7 +4,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Iterable, Iterator from my.core import Res, Stats, datetime_aware, make_logger, stat, warnings -from my.core.compat import deprecated, removeprefix, removesuffix +from my.core.compat import deprecated logger = make_logger(__name__) @@ -117,10 +117,10 @@ def _watched() -> Iterator[Res[Watched]]: # all titles contain it, so pointless to include 'Watched ' # also compatible with legacy titles - title = removeprefix(title, 'Watched ') + title = title.removeprefix('Watched ') # watches originating from some activity end with this, remove it for consistency - title = removesuffix(title, ' - YouTube') + title = title.removesuffix(' - YouTube') if YOUTUBE_VIDEO_LINK not in url: if 'youtube.com/post/' in url: diff --git a/setup.py b/setup.py index e49eee0..385c810 100644 --- a/setup.py +++ b/setup.py @@ -44,7 +44,7 @@ def main() -> None: author_email='karlicoss@gmail.com', description='A Python interface to my life', - python_requires='>=3.8', + python_requires='>=3.9', install_requires=INSTALL_REQUIRES, extras_require={ 'testing': [ From d3f9a8e8b69542361ad0838a1012a1ad10440b5b Mon Sep 17 00:00:00 2001 From: karlicoss Date: Sat, 19 Oct 2024 20:55:09 +0100 Subject: [PATCH 45/55] core: migrate code to benefit from 3.9 stuff (#401) for now keeping ruff on 3.8 target version, need to sort out modules as well --- my/core/__init__.py | 4 +- my/core/__main__.py | 97 +++++++++++++++++++++------------ my/core/_cpu_pool.py | 9 ++- my/core/_deprecated/kompress.py | 5 +- my/core/cachew.py | 29 +++++----- my/core/cfg.py | 20 +++++-- my/core/common.py | 36 ++++++------ my/core/compat.py | 7 ++- my/core/core_config.py | 33 ++++++----- my/core/denylist.py | 28 +++++----- my/core/discovery_pure.py | 19 ++++--- my/core/error.py | 43 ++++++++------- my/core/experimental.py | 6 +- my/core/freezer.py | 29 +++++----- my/core/hpi_compat.py | 13 +++-- my/core/influxdb.py | 29 +++++++--- my/core/init.py | 2 + my/core/kompress.py | 4 +- my/core/konsume.py | 39 +++++++------ my/core/mime.py | 11 ++-- my/core/orgmode.py | 8 ++- my/core/pandas.py | 7 +-- my/core/preinit.py | 1 + my/core/pytest.py | 4 +- my/core/query.py | 76 ++++++++++++-------------- my/core/query_range.py | 68 +++++++++++++---------- my/core/serialize.py | 20 ++++--- my/core/source.py | 12 +++- my/core/sqlite.py | 47 +++++++++------- my/core/stats.py | 34 +++++------- my/core/structure.py | 14 +++-- my/core/tests/auto_stats.py | 2 +- my/core/tests/common.py | 6 +- my/core/tests/denylist.py | 3 +- my/core/tests/test_cachew.py | 8 +-- my/core/tests/test_config.py | 2 +- my/core/time.py | 15 +++-- my/core/types.py | 13 +++-- my/core/util.py | 28 ++++++---- my/core/utils/concurrent.py | 7 ++- my/core/utils/imports.py | 14 ++--- my/core/utils/itertools.py | 59 +++++++++----------- my/core/warnings.py | 8 ++- 43 files changed, 515 insertions(+), 404 deletions(-) diff --git a/my/core/__init__.py b/my/core/__init__.py index ba633f6..cc549d5 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING from .cfg import make_config from .common import PathIsh, Paths, get_files from .compat import assert_never -from .error import Res, unwrap, notnone +from .error import Res, notnone, unwrap from .logging import ( make_logger, ) @@ -52,7 +52,7 @@ __all__ = [ # you could put _init_hook.py next to your private my/config # that way you can configure logging/warnings/env variables on every HPI import try: - import my._init_hook # type: ignore[import-not-found] + import my._init_hook # type: ignore[import-not-found] # noqa: F401 except: pass ## diff --git a/my/core/__main__.py b/my/core/__main__.py index 2777008..00ac4ee 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import functools import importlib import inspect @@ -7,17 +9,18 @@ import shutil import sys import tempfile import traceback +from collections.abc import Iterable, Sequence from contextlib import ExitStack from itertools import chain from pathlib import Path from subprocess import PIPE, CompletedProcess, Popen, check_call, run -from typing import Any, Callable, Iterable, List, Optional, Sequence, Type +from typing import Any, Callable import click @functools.lru_cache -def mypy_cmd() -> Optional[Sequence[str]]: +def mypy_cmd() -> Sequence[str] | None: try: # preferably, use mypy from current python env import mypy # noqa: F401 fine not to use it @@ -32,7 +35,7 @@ def mypy_cmd() -> Optional[Sequence[str]]: return None -def run_mypy(cfg_path: Path) -> Optional[CompletedProcess]: +def run_mypy(cfg_path: Path) -> CompletedProcess | None: # todo dunno maybe use the same mypy config in repository? # I'd need to install mypy.ini then?? env = {**os.environ} @@ -63,21 +66,27 @@ def eprint(x: str) -> None: # err=True prints to stderr click.echo(x, err=True) + def indent(x: str) -> str: + # todo use textwrap.indent? return ''.join(' ' + l for l in x.splitlines(keepends=True)) -OK = '✅' +OK = '✅' OFF = '🔲' + def info(x: str) -> None: eprint(OK + ' ' + x) + def error(x: str) -> None: eprint('❌ ' + x) + def warning(x: str) -> None: - eprint('❗ ' + x) # todo yellow? + eprint('❗ ' + x) # todo yellow? + def tb(e: Exception) -> None: tb = ''.join(traceback.format_exception(Exception, e, e.__traceback__)) @@ -86,6 +95,7 @@ def tb(e: Exception) -> None: def config_create() -> None: from .preinit import get_mycfg_dir + mycfg_dir = get_mycfg_dir() created = False @@ -94,7 +104,8 @@ def config_create() -> None: my_config = mycfg_dir / 'my' / 'config' / '__init__.py' my_config.parent.mkdir(parents=True) - my_config.write_text(''' + my_config.write_text( + ''' ### HPI personal config ## see # https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-modules @@ -117,7 +128,8 @@ class example: ### you can insert your own configuration below ### but feel free to delete the stuff above if you don't need ti -'''.lstrip()) +'''.lstrip() + ) info(f'created empty config: {my_config}') created = True else: @@ -130,12 +142,13 @@ class example: # todo return the config as a result? def config_ok() -> bool: - errors: List[Exception] = [] + errors: list[Exception] = [] # at this point 'my' should already be imported, so doesn't hurt to extract paths from it import my + try: - paths: List[str] = list(my.__path__) + paths: list[str] = list(my.__path__) except Exception as e: errors.append(e) error('failed to determine module import path') @@ -145,19 +158,23 @@ def config_ok() -> bool: # first try doing as much as possible without actually importing my.config from .preinit import get_mycfg_dir + cfg_path = get_mycfg_dir() # alternative is importing my.config and then getting cfg_path from its __file__/__path__ # not sure which is better tbh ## check we're not using stub config import my.core + try: core_pkg_path = str(Path(my.core.__path__[0]).parent) if str(cfg_path).startswith(core_pkg_path): - error(f''' + error( + f''' Seems that the stub config is used ({cfg_path}). This is likely not going to work. See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-modules for more information -'''.strip()) +'''.strip() + ) errors.append(RuntimeError('bad config path')) except Exception as e: errors.append(e) @@ -189,7 +206,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module ## check types mypy_res = run_mypy(cfg_path) - if mypy_res is not None: # has mypy + if mypy_res is not None: # has mypy rc = mypy_res.returncode if rc == 0: info('mypy check : success') @@ -221,7 +238,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-module from .util import HPIModule, modules -def _modules(*, all: bool=False) -> Iterable[HPIModule]: +def _modules(*, all: bool = False) -> Iterable[HPIModule]: skipped = [] for m in modules(): if not all and m.skip_reason is not None: @@ -232,7 +249,7 @@ def _modules(*, all: bool=False) -> Iterable[HPIModule]: warning(f'Skipped {len(skipped)} modules: {skipped}. Pass --all if you want to see them.') -def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: List[str]) -> None: +def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: list[str]) -> None: if len(for_modules) > 0: # if you're checking specific modules, show errors # hopefully makes sense? @@ -256,7 +273,7 @@ def modules_check(*, verbose: bool, list_all: bool, quick: bool, for_modules: Li # todo add a --all argument to disregard is_active check? for mr in mods: skip = mr.skip_reason - m = mr.name + m = mr.name if skip is not None: eprint(f'{OFF} {click.style("SKIP", fg="yellow")}: {m:<50} {skip}') continue @@ -306,8 +323,8 @@ def list_modules(*, list_all: bool) -> None: tabulate_warnings() for mr in _modules(all=list_all): - m = mr.name - sr = mr.skip_reason + m = mr.name + sr = mr.skip_reason if sr is None: pre = OK suf = '' @@ -323,17 +340,20 @@ def tabulate_warnings() -> None: Helper to avoid visual noise in hpi modules/doctor ''' import warnings + orig = warnings.formatwarning def override(*args, **kwargs) -> str: res = orig(*args, **kwargs) return ''.join(' ' + x for x in res.splitlines(keepends=True)) + warnings.formatwarning = override # TODO loggers as well? def _requires(modules: Sequence[str]) -> Sequence[str]: from .discovery_pure import module_by_name + mods = [module_by_name(module) for module in modules] res = [] for mod in mods: @@ -360,7 +380,7 @@ def module_requires(*, module: Sequence[str]) -> None: click.echo(x) -def module_install(*, user: bool, module: Sequence[str], parallel: bool=False, break_system_packages: bool=False) -> None: +def module_install(*, user: bool, module: Sequence[str], parallel: bool = False, break_system_packages: bool = False) -> None: if isinstance(module, str): # legacy behavior, used to take a since argument module = [module] @@ -437,7 +457,7 @@ def _ui_getchar_pick(choices: Sequence[str], prompt: str = 'Select from: ') -> i return result_map[ch] -def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = True) -> Iterable[Callable[..., Any]]: +def _locate_functions_or_prompt(qualified_names: list[str], *, prompt: bool = True) -> Iterable[Callable[..., Any]]: from .query import QueryException, locate_qualified_function from .stats import is_data_provider @@ -487,6 +507,7 @@ def _locate_functions_or_prompt(qualified_names: List[str], *, prompt: bool = Tr def _warn_exceptions(exc: Exception) -> None: from my.core import make_logger + logger = make_logger('CLI', level='warning') logger.exception(f'hpi query: {exc}') @@ -498,14 +519,14 @@ def query_hpi_functions( *, output: str = 'json', stream: bool = False, - qualified_names: List[str], - order_key: Optional[str], - order_by_value_type: Optional[Type], + qualified_names: list[str], + order_key: str | None, + order_by_value_type: type | None, after: Any, before: Any, within: Any, reverse: bool = False, - limit: Optional[int], + limit: int | None, drop_unsorted: bool, wrap_unsorted: bool, warn_exceptions: bool, @@ -529,7 +550,8 @@ def query_hpi_functions( warn_exceptions=warn_exceptions, warn_func=_warn_exceptions, raise_exceptions=raise_exceptions, - drop_exceptions=drop_exceptions) + drop_exceptions=drop_exceptions, + ) if output == 'json': from .serialize import dumps @@ -563,7 +585,7 @@ def query_hpi_functions( # can ignore the mypy warning here, locations_to_gpx yields any errors # if you didnt pass it something that matches the LocationProtocol - for exc in locations_to_gpx(res, sys.stdout): # type: ignore[arg-type] + for exc in locations_to_gpx(res, sys.stdout): # type: ignore[arg-type] if warn_exceptions: _warn_exceptions(exc) elif raise_exceptions: @@ -580,6 +602,7 @@ def query_hpi_functions( except ModuleNotFoundError: eprint("'repl' typically uses ipython, install it with 'python3 -m pip install ipython'. falling back to stdlib...") import code + code.interact(local=locals()) else: IPython.embed() @@ -619,13 +642,13 @@ def main(*, debug: bool) -> None: @functools.lru_cache(maxsize=1) -def _all_mod_names() -> List[str]: +def _all_mod_names() -> list[str]: """Should include all modules, in case user is trying to diagnose issues""" # sort this, so that the order doesn't change while tabbing through return sorted([m.name for m in modules()]) -def _module_autocomplete(ctx: click.Context, args: Sequence[str], incomplete: str) -> List[str]: +def _module_autocomplete(ctx: click.Context, args: Sequence[str], incomplete: str) -> list[str]: return [m for m in _all_mod_names() if m.startswith(incomplete)] @@ -784,14 +807,14 @@ def query_cmd( function_name: Sequence[str], output: str, stream: bool, - order_key: Optional[str], - order_type: Optional[str], - after: Optional[str], - before: Optional[str], - within: Optional[str], - recent: Optional[str], + order_key: str | None, + order_type: str | None, + after: str | None, + before: str | None, + within: str | None, + recent: str | None, reverse: bool, - limit: Optional[int], + limit: int | None, drop_unsorted: bool, wrap_unsorted: bool, warn_exceptions: bool, @@ -827,7 +850,7 @@ def query_cmd( from datetime import date, datetime - chosen_order_type: Optional[Type] + chosen_order_type: type | None if order_type == "datetime": chosen_order_type = datetime elif order_type == "date": @@ -863,7 +886,8 @@ def query_cmd( wrap_unsorted=wrap_unsorted, warn_exceptions=warn_exceptions, raise_exceptions=raise_exceptions, - drop_exceptions=drop_exceptions) + drop_exceptions=drop_exceptions, + ) except QueryException as qe: eprint(str(qe)) sys.exit(1) @@ -878,6 +902,7 @@ def query_cmd( def test_requires() -> None: from click.testing import CliRunner + result = CliRunner().invoke(main, ['module', 'requires', 'my.github.ghexport', 'my.browser.export']) assert result.exit_code == 0 assert "github.com/karlicoss/ghexport" in result.output diff --git a/my/core/_cpu_pool.py b/my/core/_cpu_pool.py index 2369075..6b107a7 100644 --- a/my/core/_cpu_pool.py +++ b/my/core/_cpu_pool.py @@ -10,15 +10,18 @@ how many cores we want to dedicate to the DAL. Enabled by the env variable, specifying how many cores to dedicate e.g. "HPI_CPU_POOL=4 hpi query ..." """ + +from __future__ import annotations + import os from concurrent.futures import ProcessPoolExecutor -from typing import Optional, cast +from typing import cast _NOT_SET = cast(ProcessPoolExecutor, object()) -_INSTANCE: Optional[ProcessPoolExecutor] = _NOT_SET +_INSTANCE: ProcessPoolExecutor | None = _NOT_SET -def get_cpu_pool() -> Optional[ProcessPoolExecutor]: +def get_cpu_pool() -> ProcessPoolExecutor | None: global _INSTANCE if _INSTANCE is _NOT_SET: use_cpu_pool = os.environ.get('HPI_CPU_POOL') diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index cd27a7f..ce14fad 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -1,16 +1,17 @@ """ Various helpers for compression """ + # fmt: off from __future__ import annotations import io import pathlib -import sys +from collections.abc import Iterator, Sequence from datetime import datetime from functools import total_ordering from pathlib import Path -from typing import IO, Any, Iterator, Sequence, Union +from typing import IO, Any, Union PathIsh = Union[Path, str] diff --git a/my/core/cachew.py b/my/core/cachew.py index dc6ed79..9ccee09 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -1,16 +1,18 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations + +from .internal import assert_subpackage + +assert_subpackage(__name__) import logging import sys +from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from typing import ( TYPE_CHECKING, Any, Callable, - Iterator, - Optional, - Type, TypeVar, Union, cast, @@ -21,7 +23,6 @@ import appdirs # type: ignore[import-untyped] from . import warnings - PathIsh = Union[str, Path] # avoid circular import from .common @@ -60,12 +61,12 @@ def _appdirs_cache_dir() -> Path: _CACHE_DIR_NONE_HACK = Path('/tmp/hpi/cachew_none_hack') -def cache_dir(suffix: Optional[PathIsh] = None) -> Path: +def cache_dir(suffix: PathIsh | None = None) -> Path: from . import core_config as CC cdir_ = CC.config.get_cache_dir() - sp: Optional[Path] = None + sp: Path | None = None if suffix is not None: sp = Path(suffix) # guess if you do need absolute, better path it directly instead of as suffix? @@ -144,21 +145,19 @@ if TYPE_CHECKING: # we need two versions due to @doublewrap # this is when we just annotate as @cachew without any args @overload # type: ignore[no-overload-impl] - def mcachew(fun: F) -> F: - ... + def mcachew(fun: F) -> F: ... @overload def mcachew( - cache_path: Optional[PathProvider] = ..., + cache_path: PathProvider | None = ..., *, force_file: bool = ..., - cls: Optional[Type] = ..., + cls: type | None = ..., depends_on: HashFunction = ..., - logger: Optional[logging.Logger] = ..., + logger: logging.Logger | None = ..., chunk_by: int = ..., - synthetic_key: Optional[str] = ..., - ) -> Callable[[F], F]: - ... + synthetic_key: str | None = ..., + ) -> Callable[[F], F]: ... else: mcachew = _mcachew_impl diff --git a/my/core/cfg.py b/my/core/cfg.py index a71a7e3..9851443 100644 --- a/my/core/cfg.py +++ b/my/core/cfg.py @@ -3,28 +3,32 @@ from __future__ import annotations import importlib import re import sys +from collections.abc import Iterator from contextlib import ExitStack, contextmanager -from typing import Any, Callable, Dict, Iterator, Optional, Type, TypeVar +from typing import Any, Callable, TypeVar -Attrs = Dict[str, Any] +Attrs = dict[str, Any] C = TypeVar('C') + # todo not sure about it, could be overthinking... # but short enough to change later # TODO document why it's necessary? -def make_config(cls: Type[C], migration: Callable[[Attrs], Attrs]=lambda x: x) -> C: +def make_config(cls: type[C], migration: Callable[[Attrs], Attrs] = lambda x: x) -> C: user_config = cls.__base__ old_props = { # NOTE: deliberately use gettatr to 'force' class properties here - k: getattr(user_config, k) for k in vars(user_config) + k: getattr(user_config, k) + for k in vars(user_config) } new_props = migration(old_props) from dataclasses import fields + params = { k: v for k, v in new_props.items() - if k in {f.name for f in fields(cls)} # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 + if k in {f.name for f in fields(cls)} # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 } # todo maybe return type here? return cls(**params) @@ -51,6 +55,8 @@ def _override_config(config: F) -> Iterator[F]: ModuleRegex = str + + @contextmanager def _reload_modules(modules: ModuleRegex) -> Iterator[None]: # need to use list here, otherwise reordering with set might mess things up @@ -81,13 +87,14 @@ def _reload_modules(modules: ModuleRegex) -> Iterator[None]: @contextmanager -def tmp_config(*, modules: Optional[ModuleRegex]=None, config=None): +def tmp_config(*, modules: ModuleRegex | None = None, config=None): if modules is None: assert config is None if modules is not None: assert config is not None import my.config + with ExitStack() as module_reload_stack, _override_config(my.config) as new_config: if config is not None: overrides = {k: v for k, v in vars(config).items() if not k.startswith('__')} @@ -102,6 +109,7 @@ def tmp_config(*, modules: Optional[ModuleRegex]=None, config=None): def test_tmp_config() -> None: class extra: data_path = '/path/to/data' + with tmp_config() as c: assert c.google != 'whatever' assert not hasattr(c, 'extra') diff --git a/my/core/common.py b/my/core/common.py index a2c2ad3..91fe9bd 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -1,20 +1,18 @@ +from __future__ import annotations + import os +from collections.abc import Iterable, Sequence from glob import glob as do_glob from pathlib import Path from typing import ( TYPE_CHECKING, Callable, Generic, - Iterable, - List, - Sequence, - Tuple, TypeVar, Union, ) -from . import compat -from . import warnings +from . import compat, warnings # some helper functions # TODO start deprecating this? soon we'd be able to use Path | str syntax which is shorter and more explicit @@ -24,20 +22,22 @@ Paths = Union[Sequence[PathIsh], PathIsh] DEFAULT_GLOB = '*' + + def get_files( pp: Paths, - glob: str=DEFAULT_GLOB, + glob: str = DEFAULT_GLOB, *, - sort: bool=True, - guess_compression: bool=True, -) -> Tuple[Path, ...]: + sort: bool = True, + guess_compression: bool = True, +) -> tuple[Path, ...]: """ Helper function to avoid boilerplate. Tuple as return type is a bit friendlier for hashing/caching, so hopefully makes sense """ # TODO FIXME mm, some wrapper to assert iterator isn't empty? - sources: List[Path] + sources: list[Path] if isinstance(pp, Path): sources = [pp] elif isinstance(pp, str): @@ -54,7 +54,7 @@ def get_files( # TODO ugh. very flaky... -3 because [, get_files(), ] return traceback.extract_stack()[-3].filename - paths: List[Path] = [] + paths: list[Path] = [] for src in sources: if src.parts[0] == '~': src = src.expanduser() @@ -64,7 +64,7 @@ def get_files( if glob != DEFAULT_GLOB: warnings.medium(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") paths.extend(map(Path, do_glob(gs))) - elif os.path.isdir(str(src)): + elif os.path.isdir(str(src)): # noqa: PTH112 # NOTE: we're using os.path here on purpose instead of src.is_dir # the reason is is_dir for archives might return True and then # this clause would try globbing insize the archives @@ -234,16 +234,14 @@ if not TYPE_CHECKING: return types.asdict(*args, **kwargs) # todo wrap these in deprecated decorator as well? + # TODO hmm how to deprecate these in runtime? + # tricky cause they are actually classes/types + from typing import Literal # noqa: F401 + from .cachew import mcachew # noqa: F401 # this is kinda internal, should just use my.core.logging.setup_logger if necessary from .logging import setup_logger - - # TODO hmm how to deprecate these in runtime? - # tricky cause they are actually classes/types - - from typing import Literal # noqa: F401 - from .stats import Stats from .types import ( Json, diff --git a/my/core/compat.py b/my/core/compat.py index 3273ff4..8f719a8 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -3,6 +3,8 @@ Contains backwards compatibility helpers for different python versions. If something is relevant to HPI itself, please put it in .hpi_compat instead ''' +from __future__ import annotations + import sys from typing import TYPE_CHECKING @@ -29,6 +31,7 @@ if not TYPE_CHECKING: @deprecated('use .removesuffix method on string directly instead') def removesuffix(text: str, suffix: str) -> str: return text.removesuffix(suffix) + ## ## used to have compat function before 3.8 for these, keeping for runtime back compatibility @@ -46,13 +49,13 @@ else: # bisect_left doesn't have a 'key' parameter (which we use) # till python3.10 if sys.version_info[:2] <= (3, 9): - from typing import Any, Callable, List, Optional, TypeVar + from typing import Any, Callable, List, Optional, TypeVar # noqa: UP035 X = TypeVar('X') # copied from python src # fmt: off - def bisect_left(a: List[Any], x: Any, lo: int=0, hi: Optional[int]=None, *, key: Optional[Callable[..., Any]]=None) -> int: + def bisect_left(a: list[Any], x: Any, lo: int=0, hi: int | None=None, *, key: Callable[..., Any] | None=None) -> int: if lo < 0: raise ValueError('lo must be non-negative') if hi is None: diff --git a/my/core/core_config.py b/my/core/core_config.py index 9036971..3f26c03 100644 --- a/my/core/core_config.py +++ b/my/core/core_config.py @@ -2,18 +2,21 @@ Bindings for the 'core' HPI configuration ''' +from __future__ import annotations + import re +from collections.abc import Sequence from dataclasses import dataclass from pathlib import Path -from typing import Optional, Sequence -from . import PathIsh, warnings +from . import warnings try: from my.config import core as user_config # type: ignore[attr-defined] 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: # make it defensive, because it's pretty commonly used and would be annoying if it breaks hpi doctor etc. @@ -24,6 +27,7 @@ except Exception as e: _HPI_CACHE_DIR_DEFAULT = '' + @dataclass class Config(user_config): ''' @@ -34,7 +38,7 @@ class Config(user_config): cache_dir = '/your/custom/cache/path' ''' - cache_dir: Optional[PathIsh] = _HPI_CACHE_DIR_DEFAULT + cache_dir: Path | str | None = _HPI_CACHE_DIR_DEFAULT ''' Base directory for cachew. - if None , means cache is disabled @@ -44,7 +48,7 @@ class Config(user_config): NOTE: you shouldn't use this attribute in HPI modules directly, use Config.get_cache_dir()/cachew.cache_dir() instead ''' - tmp_dir: Optional[PathIsh] = None + tmp_dir: Path | str | None = None ''' Path to a temporary directory. This can be used temporarily while extracting zipfiles etc... @@ -52,34 +56,36 @@ class Config(user_config): - otherwise , use the specified directory as the base temporary directory ''' - enabled_modules : Optional[Sequence[str]] = None + enabled_modules: Sequence[str] | None = None ''' list of regexes/globs - None means 'rely on disabled_modules' ''' - disabled_modules: Optional[Sequence[str]] = None + disabled_modules: Sequence[str] | None = None ''' list of regexes/globs - None means 'rely on enabled_modules' ''' - def get_cache_dir(self) -> Optional[Path]: + def get_cache_dir(self) -> Path | None: cdir = self.cache_dir if cdir is None: return None if cdir == _HPI_CACHE_DIR_DEFAULT: from .cachew import _appdirs_cache_dir + return _appdirs_cache_dir() else: return Path(cdir).expanduser() def get_tmp_dir(self) -> Path: - tdir: Optional[PathIsh] = self.tmp_dir + tdir: Path | str | None = self.tmp_dir tpath: Path # use tempfile if unset if tdir is None: import tempfile + tpath = Path(tempfile.gettempdir()) / 'HPI' else: tpath = Path(tdir) @@ -87,10 +93,10 @@ class Config(user_config): tpath.mkdir(parents=True, exist_ok=True) return tpath - def _is_module_active(self, module: str) -> Optional[bool]: + def _is_module_active(self, module: str) -> bool | None: # None means the config doesn't specify anything # todo might be nice to return the 'reason' too? e.g. which option has matched - def matches(specs: Sequence[str]) -> Optional[str]: + def matches(specs: Sequence[str]) -> str | None: for spec in specs: # not sure because . (packages separate) matches anything, but I guess unlikely to clash if re.match(spec, module): @@ -106,10 +112,10 @@ class Config(user_config): return None else: return False - else: # not None + else: # not None if off is None: return True - else: # not None + else: # not None # fallback onto the 'enable everything', then the user will notice warnings.medium(f"[module]: conflicting regexes '{on}' and '{off}' are set in the config. Please only use one of them.") return True @@ -121,8 +127,8 @@ config = make_config(Config) ### tests start +from collections.abc import Iterator from contextlib import contextmanager as ctx -from typing import Iterator @ctx @@ -163,4 +169,5 @@ def test_active_modules() -> None: assert cc._is_module_active("my.body.exercise") is True assert len(record_warnings) == 1 + ### tests end diff --git a/my/core/denylist.py b/my/core/denylist.py index 92faf2c..c92f9a0 100644 --- a/my/core/denylist.py +++ b/my/core/denylist.py @@ -5,23 +5,25 @@ A helper module for defining denylists for sources programmatically For docs, see doc/DENYLIST.md """ +from __future__ import annotations + import functools import json import sys from collections import defaultdict +from collections.abc import Iterator, Mapping from pathlib import Path -from typing import Any, Dict, Iterator, List, Mapping, Set, TypeVar +from typing import Any, TypeVar import click from more_itertools import seekable -from my.core.common import PathIsh -from my.core.serialize import dumps -from my.core.warnings import medium +from .serialize import dumps +from .warnings import medium T = TypeVar("T") -DenyMap = Mapping[str, Set[Any]] +DenyMap = Mapping[str, set[Any]] def _default_key_func(obj: T) -> str: @@ -29,9 +31,9 @@ def _default_key_func(obj: T) -> str: class DenyList: - def __init__(self, denylist_file: PathIsh): + def __init__(self, denylist_file: Path | str) -> None: self.file = Path(denylist_file).expanduser().absolute() - self._deny_raw_list: List[Dict[str, Any]] = [] + self._deny_raw_list: list[dict[str, Any]] = [] self._deny_map: DenyMap = defaultdict(set) # deny cli, user can override these @@ -45,7 +47,7 @@ class DenyList: return deny_map: DenyMap = defaultdict(set) - data: List[Dict[str, Any]]= json.loads(self.file.read_text()) + data: list[dict[str, Any]] = json.loads(self.file.read_text()) self._deny_raw_list = data for ignore in data: @@ -112,7 +114,7 @@ class DenyList: self._load() self._deny_raw({key: self._stringify_value(value)}, write=write) - def _deny_raw(self, data: Dict[str, Any], *, write: bool = False) -> None: + def _deny_raw(self, data: dict[str, Any], *, write: bool = False) -> None: self._deny_raw_list.append(data) if write: self.write() @@ -131,7 +133,7 @@ class DenyList: def _deny_cli_remember( self, items: Iterator[T], - mem: Dict[str, T], + mem: dict[str, T], ) -> Iterator[str]: keyf = self._deny_cli_key_func or _default_key_func # i.e., convert each item to a string, and map str -> item @@ -157,10 +159,8 @@ class DenyList: # reset the iterator sit.seek(0) # so we can map the selected string from fzf back to the original objects - memory_map: Dict[str, T] = {} - picker = FzfPrompt( - executable_path=self.fzf_path, default_options="--no-multi" - ) + memory_map: dict[str, T] = {} + picker = FzfPrompt(executable_path=self.fzf_path, default_options="--no-multi") picked_l = picker.prompt( self._deny_cli_remember(itr, memory_map), "--read0", diff --git a/my/core/discovery_pure.py b/my/core/discovery_pure.py index b753de8..18a19c4 100644 --- a/my/core/discovery_pure.py +++ b/my/core/discovery_pure.py @@ -10,6 +10,8 @@ This potentially allows it to be: It should be free of external modules, importlib, exec, etc. etc. ''' +from __future__ import annotations + REQUIRES = 'REQUIRES' NOT_HPI_MODULE_VAR = '__NOT_HPI_MODULE__' @@ -19,8 +21,9 @@ import ast import logging import os import re +from collections.abc import Iterable, Sequence from pathlib import Path -from typing import Any, Iterable, List, NamedTuple, Optional, Sequence, cast +from typing import Any, NamedTuple, Optional, cast ''' None means that requirements weren't defined (different from empty requirements) @@ -30,11 +33,11 @@ Requires = Optional[Sequence[str]] class HPIModule(NamedTuple): name: str - skip_reason: Optional[str] - doc: Optional[str] = None - file: Optional[Path] = None + skip_reason: str | None + doc: str | None = None + file: Path | None = None requires: Requires = None - legacy: Optional[str] = None # contains reason/deprecation warning + legacy: str | None = None # contains reason/deprecation warning def ignored(m: str) -> bool: @@ -55,13 +58,13 @@ def has_stats(src: Path) -> bool: def _has_stats(code: str) -> bool: a: ast.Module = ast.parse(code) for x in a.body: - try: # maybe assign + try: # maybe assign [tg] = cast(Any, x).targets if tg.id == 'stats': return True except: pass - try: # maybe def? + try: # maybe def? name = cast(Any, x).name if name == 'stats': return True @@ -144,7 +147,7 @@ def all_modules() -> Iterable[HPIModule]: def _iter_my_roots() -> Iterable[Path]: import my # doesn't import any code, because of namespace package - paths: List[str] = list(my.__path__) + paths: list[str] = list(my.__path__) if len(paths) == 0: # should probably never happen?, if this code is running, it was imported # because something was added to __path__ to match this name diff --git a/my/core/error.py b/my/core/error.py index ed26dda..b308869 100644 --- a/my/core/error.py +++ b/my/core/error.py @@ -3,19 +3,16 @@ Various error handling helpers See https://beepb00p.xyz/mypy-error-handling.html#kiss for more detail """ +from __future__ import annotations + import traceback +from collections.abc import Iterable, Iterator from datetime import datetime from itertools import tee from typing import ( Any, Callable, - Iterable, - Iterator, - List, Literal, - Optional, - Tuple, - Type, TypeVar, Union, cast, @@ -33,7 +30,7 @@ Res = ResT[T, Exception] ErrorPolicy = Literal["yield", "raise", "drop"] -def notnone(x: Optional[T]) -> T: +def notnone(x: T | None) -> T: assert x is not None return x @@ -60,13 +57,15 @@ def raise_exceptions(itr: Iterable[Res[T]]) -> Iterator[T]: yield o -def warn_exceptions(itr: Iterable[Res[T]], warn_func: Optional[Callable[[Exception], None]] = None) -> Iterator[T]: +def warn_exceptions(itr: Iterable[Res[T]], warn_func: Callable[[Exception], None] | None = None) -> Iterator[T]: # if not provided, use the 'warnings' module if warn_func is None: from my.core.warnings import medium + def _warn_func(e: Exception) -> None: # TODO: print traceback? but user could always --raise-exceptions as well medium(str(e)) + warn_func = _warn_func for o in itr: @@ -81,7 +80,7 @@ def echain(ex: E, cause: Exception) -> E: return ex -def split_errors(l: Iterable[ResT[T, E]], ET: Type[E]) -> Tuple[Iterable[T], Iterable[E]]: +def split_errors(l: Iterable[ResT[T, E]], ET: type[E]) -> tuple[Iterable[T], Iterable[E]]: # TODO would be nice to have ET=Exception default? but it causes some mypy complaints? vit, eit = tee(l) # TODO ugh, not sure if I can reconcile type checking and runtime and convince mypy that ET and E are the same type? @@ -99,7 +98,9 @@ def split_errors(l: Iterable[ResT[T, E]], ET: Type[E]) -> Tuple[Iterable[T], Ite K = TypeVar('K') -def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T]]: + + +def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> list[Res[T]]: """ Sort a sequence potentially interleaved with errors/entries on which the key can't be computed. The general idea is: the error sticks to the non-error entry that follows it @@ -107,7 +108,7 @@ def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T] group = [] groups = [] for i in items: - k: Optional[K] + k: K | None try: k = key(i) except Exception: # error white computing key? dunno, might be nice to handle... @@ -117,10 +118,10 @@ def sort_res_by(items: Iterable[Res[T]], key: Callable[[Any], K]) -> List[Res[T] groups.append((k, group)) group = [] - results: List[Res[T]] = [] - for _v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? + results: list[Res[T]] = [] + for _v, grp in sorted(groups, key=lambda p: p[0]): # type: ignore[return-value, arg-type] # TODO SupportsLessThan?? results.extend(grp) - results.extend(group) # handle last group (it will always be errors only) + results.extend(group) # handle last group (it will always be errors only) return results @@ -162,20 +163,20 @@ def test_sort_res_by() -> None: # helpers to associate timestamps with the errors (so something meaningful could be displayed on the plots, for example) # todo document it under 'patterns' somewhere... # todo proper typevar? -def set_error_datetime(e: Exception, dt: Optional[datetime]) -> None: +def set_error_datetime(e: Exception, dt: datetime | None) -> None: if dt is None: return e.args = (*e.args, dt) # todo not sure if should return new exception? -def attach_dt(e: Exception, *, dt: Optional[datetime]) -> Exception: +def attach_dt(e: Exception, *, dt: datetime | None) -> Exception: set_error_datetime(e, dt) return e # todo it might be problematic because might mess with timezones (when it's converted to string, it's converted to a shift) -def extract_error_datetime(e: Exception) -> Optional[datetime]: +def extract_error_datetime(e: Exception) -> datetime | None: import re for x in reversed(e.args): @@ -201,10 +202,10 @@ MODULE_SETUP_URL = 'https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#p def warn_my_config_import_error( - err: Union[ImportError, AttributeError], + err: ImportError | AttributeError, *, - help_url: Optional[str] = None, - module_name: Optional[str] = None, + help_url: str | None = None, + module_name: str | None = None, ) -> bool: """ If the user tried to import something from my.config but it failed, @@ -265,7 +266,7 @@ def test_datetime_errors() -> None: import pytz # noqa: I001 dt_notz = datetime.now() - dt_tz = datetime.now(tz=pytz.timezone('Europe/Amsterdam')) + dt_tz = datetime.now(tz=pytz.timezone('Europe/Amsterdam')) for dt in [dt_tz, dt_notz]: e1 = RuntimeError('whatever') assert extract_error_datetime(e1) is None diff --git a/my/core/experimental.py b/my/core/experimental.py index 1a78272..0a1c3b4 100644 --- a/my/core/experimental.py +++ b/my/core/experimental.py @@ -1,6 +1,8 @@ +from __future__ import annotations + import sys import types -from typing import Any, Dict, Optional +from typing import Any # The idea behind this one is to support accessing "overlaid/shadowed" modules from namespace packages @@ -20,7 +22,7 @@ def import_original_module( file: str, *, star: bool = False, - globals: Optional[Dict[str, Any]] = None, + globals: dict[str, Any] | None = None, ) -> types.ModuleType: module_to_restore = sys.modules[module_name] diff --git a/my/core/freezer.py b/my/core/freezer.py index 93bceb7..4fb0e25 100644 --- a/my/core/freezer.py +++ b/my/core/freezer.py @@ -1,29 +1,29 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations -import dataclasses as dcl +from .internal import assert_subpackage + +assert_subpackage(__name__) + +import dataclasses import inspect -from typing import Any, Type, TypeVar +from typing import Any, Generic, TypeVar D = TypeVar('D') -def _freeze_dataclass(Orig: Type[D]): - ofields = [(f.name, f.type, f) for f in dcl.fields(Orig)] # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 +def _freeze_dataclass(Orig: type[D]): + ofields = [(f.name, f.type, f) for f in dataclasses.fields(Orig)] # type: ignore[arg-type] # see https://github.com/python/typing_extensions/issues/115 # extract properties along with their types - props = list(inspect.getmembers(Orig, lambda o: isinstance(o, property))) + props = list(inspect.getmembers(Orig, lambda o: isinstance(o, property))) pfields = [(name, inspect.signature(getattr(prop, 'fget')).return_annotation) for name, prop in props] # FIXME not sure about name? # NOTE: sadly passing bases=[Orig] won't work, python won't let us override properties with fields - RRR = dcl.make_dataclass('RRR', fields=[*ofields, *pfields]) + RRR = dataclasses.make_dataclass('RRR', fields=[*ofields, *pfields]) # todo maybe even declare as slots? return props, RRR -# todo need some decorator thingie? -from typing import Generic - - class Freezer(Generic[D]): ''' Some magic which converts dataclass properties into fields. @@ -31,13 +31,13 @@ class Freezer(Generic[D]): For now only supports dataclasses. ''' - def __init__(self, Orig: Type[D]) -> None: + def __init__(self, Orig: type[D]) -> None: self.Orig = Orig self.props, self.Frozen = _freeze_dataclass(Orig) def freeze(self, value: D) -> D: pvalues = {name: getattr(value, name) for name, _ in self.props} - return self.Frozen(**dcl.asdict(value), **pvalues) # type: ignore[call-overload] # see https://github.com/python/typing_extensions/issues/115 + return self.Frozen(**dataclasses.asdict(value), **pvalues) # type: ignore[call-overload] # see https://github.com/python/typing_extensions/issues/115 ### tests @@ -45,7 +45,7 @@ class Freezer(Generic[D]): # this needs to be defined here to prevent a mypy bug # see https://github.com/python/mypy/issues/7281 -@dcl.dataclass +@dataclasses.dataclass class _A: x: Any @@ -71,6 +71,7 @@ def test_freezer() -> None: assert fd['typed'] == 123 assert fd['untyped'] == [1, 2, 3] + ### # TODO shit. what to do with exceptions? diff --git a/my/core/hpi_compat.py b/my/core/hpi_compat.py index 949046d..3687483 100644 --- a/my/core/hpi_compat.py +++ b/my/core/hpi_compat.py @@ -3,11 +3,14 @@ Contains various backwards compatibility/deprecation helpers relevant to HPI its (as opposed to .compat module which implements compatibility between python versions) """ +from __future__ import annotations + import inspect import os import re +from collections.abc import Iterator, Sequence from types import ModuleType -from typing import Iterator, List, Optional, Sequence, TypeVar +from typing import TypeVar from . import warnings @@ -15,7 +18,7 @@ from . import warnings def handle_legacy_import( parent_module_name: str, legacy_submodule_name: str, - parent_module_path: List[str], + parent_module_path: list[str], ) -> bool: ### # this is to trick mypy into treating this as a proper namespace package @@ -122,8 +125,8 @@ class always_supports_sequence(Iterator[V]): def __init__(self, it: Iterator[V]) -> None: self._it = it - self._list: Optional[List[V]] = None - self._lit: Optional[Iterator[V]] = None + self._list: list[V] | None = None + self._lit: Iterator[V] | None = None def __iter__(self) -> Iterator[V]: # noqa: PYI034 if self._list is not None: @@ -142,7 +145,7 @@ class always_supports_sequence(Iterator[V]): return getattr(self._it, name) @property - def _aslist(self) -> List[V]: + def _aslist(self) -> list[V]: if self._list is None: qualname = getattr(self._it, '__qualname__', '') # defensive just in case warnings.medium(f'Using {qualname} as list is deprecated. Migrate to iterative processing or call list() explicitly.') diff --git a/my/core/influxdb.py b/my/core/influxdb.py index 25eeba1..78a439a 100644 --- a/my/core/influxdb.py +++ b/my/core/influxdb.py @@ -2,9 +2,14 @@ TODO doesn't really belong to 'core' morally, but can think of moving out later ''' -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations -from typing import Any, Dict, Iterable, Optional +from .internal import assert_subpackage + +assert_subpackage(__name__) + +from collections.abc import Iterable +from typing import Any import click @@ -21,7 +26,7 @@ class config: RESET_DEFAULT = False -def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_col: str='dt') -> None: +def fill(it: Iterable[Any], *, measurement: str, reset: bool = RESET_DEFAULT, dt_col: str = 'dt') -> None: # todo infer dt column automatically, reuse in stat? # it doesn't like dots, ends up some syntax error? measurement = measurement.replace('.', '_') @@ -30,6 +35,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c db = config.db from influxdb import InfluxDBClient # type: ignore + client = InfluxDBClient() # todo maybe create if not exists? # client.create_database(db) @@ -40,7 +46,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c client.delete_series(database=db, measurement=measurement) # TODO need to take schema here... - cache: Dict[str, bool] = {} + cache: dict[str, bool] = {} def good(f, v) -> bool: c = cache.get(f) @@ -59,9 +65,9 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c def dit() -> Iterable[Json]: for i in it: d = asdict(i) - tags: Optional[Json] = None - tags_ = d.get('tags') # meh... handle in a more robust manner - if tags_ is not None and isinstance(tags_, dict): # FIXME meh. + tags: Json | None = None + tags_ = d.get('tags') # meh... handle in a more robust manner + if tags_ is not None and isinstance(tags_, dict): # FIXME meh. del d['tags'] tags = tags_ @@ -84,6 +90,7 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c } from more_itertools import chunked + # "The optimal batch size is 5000 lines of line protocol." # some chunking is def necessary, otherwise it fails inserted = 0 @@ -97,9 +104,9 @@ def fill(it: Iterable[Any], *, measurement: str, reset: bool=RESET_DEFAULT, dt_c # todo "Specify timestamp precision when writing to InfluxDB."? -def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> None: +def magic_fill(it, *, name: str | None = None, reset: bool = RESET_DEFAULT) -> None: if name is None: - assert callable(it) # generators have no name/module + assert callable(it) # generators have no name/module name = f'{it.__module__}:{it.__name__}' assert name is not None @@ -109,6 +116,7 @@ def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> No from itertools import tee from more_itertools import first, one + it, x = tee(it) f = first(x, default=None) if f is None: @@ -118,9 +126,11 @@ def magic_fill(it, *, name: Optional[str]=None, reset: bool=RESET_DEFAULT) -> No # TODO can we reuse pandas code or something? # from .pandas import _as_columns + schema = _as_columns(type(f)) from datetime import datetime + dtex = RuntimeError(f'expected single datetime field. schema: {schema}') dtf = one((f for f, t in schema.items() if t == datetime), too_short=dtex, too_long=dtex) @@ -137,6 +147,7 @@ def main() -> None: @click.argument('FUNCTION_NAME', type=str, required=True) def populate(*, function_name: str, reset: bool) -> None: from .__main__ import _locate_functions_or_prompt + [provider] = list(_locate_functions_or_prompt([function_name])) # todo could have a non-interactive version which populates from all data sources for the provider? magic_fill(provider, reset=reset) diff --git a/my/core/init.py b/my/core/init.py index 7a30955..644c7b4 100644 --- a/my/core/init.py +++ b/my/core/init.py @@ -19,6 +19,7 @@ def setup_config() -> None: from pathlib import Path from .preinit import get_mycfg_dir + mycfg_dir = get_mycfg_dir() if not mycfg_dir.exists(): @@ -43,6 +44,7 @@ See https://github.com/karlicoss/HPI/blob/master/doc/SETUP.org#setting-up-the-mo except ImportError as ex: # just in case... who knows what crazy setup users have import logging + logging.exception(ex) warnings.warn(f""" Importing 'my.config' failed! (error: {ex}). This is likely to result in issues. diff --git a/my/core/kompress.py b/my/core/kompress.py index 7cbf310..8accb2d 100644 --- a/my/core/kompress.py +++ b/my/core/kompress.py @@ -1,4 +1,6 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage + +assert_subpackage(__name__) from . import warnings diff --git a/my/core/konsume.py b/my/core/konsume.py index 0e4a2fe..6d24167 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -5,17 +5,21 @@ This can potentially allow both for safer defensive parsing, and let you know if TODO perhaps need to get some inspiration from linear logic to decide on a nice API... ''' +from __future__ import annotations + from collections import OrderedDict -from typing import Any, List +from typing import Any def ignore(w, *keys): for k in keys: w[k].ignore() + def zoom(w, *keys): return [w[k].zoom() for k in keys] + # TODO need to support lists class Zoomable: def __init__(self, parent, *args, **kwargs) -> None: @@ -40,7 +44,7 @@ class Zoomable: assert self.parent is not None self.parent._remove(self) - def zoom(self) -> 'Zoomable': + def zoom(self) -> Zoomable: self.consume() return self @@ -63,6 +67,7 @@ class Wdict(Zoomable, OrderedDict): def this_consumed(self): return len(self) == 0 + # TODO specify mypy type for the index special method? @@ -77,6 +82,7 @@ class Wlist(Zoomable, list): def this_consumed(self): return len(self) == 0 + class Wvalue(Zoomable): def __init__(self, parent, value: Any) -> None: super().__init__(parent) @@ -87,23 +93,20 @@ class Wvalue(Zoomable): return [] def this_consumed(self): - return True # TODO not sure.. + return True # TODO not sure.. def __repr__(self): return 'WValue{' + repr(self.value) + '}' -from typing import Tuple - - -def _wrap(j, parent=None) -> Tuple[Zoomable, List[Zoomable]]: +def _wrap(j, parent=None) -> tuple[Zoomable, list[Zoomable]]: res: Zoomable - cc: List[Zoomable] + cc: list[Zoomable] if isinstance(j, dict): res = Wdict(parent) cc = [res] for k, v in j.items(): - vv, c = _wrap(v, parent=res) + vv, c = _wrap(v, parent=res) res[k] = vv cc.extend(c) return res, cc @@ -122,13 +125,14 @@ 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 -from typing import Iterator class UnconsumedError(Exception): pass + # TODO think about error policy later... @contextmanager def wrap(j, *, throw=True) -> Iterator[Zoomable]: @@ -137,7 +141,7 @@ def wrap(j, *, throw=True) -> Iterator[Zoomable]: yield w for c in children: - if not c.this_consumed(): # TODO hmm. how does it figure out if it's consumed??? + if not c.this_consumed(): # TODO hmm. how does it figure out if it's consumed??? if throw: # TODO need to keep a full path or something... raise UnconsumedError(f''' @@ -153,6 +157,7 @@ from typing import cast def test_unconsumed() -> None: import pytest + with pytest.raises(UnconsumedError): with wrap({'a': 1234}) as w: w = cast(Wdict, w) @@ -163,6 +168,7 @@ def test_unconsumed() -> None: w = cast(Wdict, w) d = w['c']['d'].zoom() + def test_consumed() -> None: with wrap({'a': 1234}) as w: w = cast(Wdict, w) @@ -173,6 +179,7 @@ def test_consumed() -> None: c = w['c'].zoom() d = c['d'].zoom() + def test_types() -> None: # (string, number, object, array, boolean or nul with wrap({'string': 'string', 'number': 3.14, 'boolean': True, 'null': None, 'list': [1, 2, 3]}) as w: @@ -181,9 +188,10 @@ def test_types() -> None: w['number'].consume() w['boolean'].zoom() w['null'].zoom() - for x in list(w['list'].zoom()): # TODO eh. how to avoid the extra list thing? + for x in list(w['list'].zoom()): # TODO eh. how to avoid the extra list thing? x.consume() + def test_consume_all() -> None: with wrap({'aaa': {'bbb': {'hi': 123}}}) as w: w = cast(Wdict, w) @@ -193,11 +201,9 @@ def test_consume_all() -> None: def test_consume_few() -> None: import pytest + pytest.skip('Will think about it later..') - with wrap({ - 'important': 123, - 'unimportant': 'whatever' - }) as w: + with wrap({'important': 123, 'unimportant': 'whatever'}) as w: w = cast(Wdict, w) w['important'].zoom() w.consume_all() @@ -206,6 +212,7 @@ def test_consume_few() -> None: def test_zoom() -> None: import pytest + with wrap({'aaa': 'whatever'}) as w: w = cast(Wdict, w) with pytest.raises(KeyError): diff --git a/my/core/mime.py b/my/core/mime.py index cf5bdf5..8235960 100644 --- a/my/core/mime.py +++ b/my/core/mime.py @@ -2,11 +2,14 @@ Utils for mime/filetype handling """ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations + +from .internal import assert_subpackage + +assert_subpackage(__name__) import functools - -from .common import PathIsh +from pathlib import Path @functools.lru_cache(1) @@ -23,7 +26,7 @@ import mimetypes # todo do I need init()? # todo wtf? fastermime thinks it's mime is application/json even if the extension is xz?? # whereas magic detects correctly: application/x-zstd and application/x-xz -def fastermime(path: PathIsh) -> str: +def fastermime(path: Path | str) -> str: paths = str(path) # mimetypes is faster, so try it first (mime, _) = mimetypes.guess_type(paths) diff --git a/my/core/orgmode.py b/my/core/orgmode.py index 979f288..96c09a4 100644 --- a/my/core/orgmode.py +++ b/my/core/orgmode.py @@ -1,6 +1,7 @@ """ Various helpers for reading org-mode data """ + from datetime import datetime @@ -22,17 +23,20 @@ def parse_org_datetime(s: str) -> datetime: # TODO I guess want to borrow inspiration from bs4? element type <-> tag; and similar logic for find_one, find_all -from typing import Callable, Iterable, TypeVar +from collections.abc import Iterable +from typing import Callable, TypeVar from orgparse import OrgNode V = TypeVar('V') + def collect(n: OrgNode, cfun: Callable[[OrgNode], Iterable[V]]) -> Iterable[V]: yield from cfun(n) for c in n.children: yield from collect(c, cfun) + from more_itertools import one from orgparse.extra import Table @@ -46,7 +50,7 @@ class TypedTable(Table): tt = super().__new__(TypedTable) tt.__dict__ = orig.__dict__ blocks = list(orig.blocks) - header = blocks[0] # fist block is schema + header = blocks[0] # fist block is schema if len(header) == 2: # TODO later interpret first line as types header = header[1:] diff --git a/my/core/pandas.py b/my/core/pandas.py index 8f5fd29..d444965 100644 --- a/my/core/pandas.py +++ b/my/core/pandas.py @@ -7,17 +7,14 @@ from __future__ import annotations # todo not sure if belongs to 'core'. It's certainly 'more' core than actual modules, but still not essential # NOTE: this file is meant to be importable without Pandas installed import dataclasses +from collections.abc import Iterable, Iterator from datetime import datetime, timezone from pprint import pformat from typing import ( TYPE_CHECKING, Any, Callable, - Dict, - Iterable, - Iterator, Literal, - Type, TypeVar, ) @@ -178,7 +175,7 @@ def _to_jsons(it: Iterable[Res[Any]]) -> Iterable[Json]: Schema = Any -def _as_columns(s: Schema) -> Dict[str, Type]: +def _as_columns(s: Schema) -> dict[str, type]: # todo would be nice to extract properties; add tests for this as well if dataclasses.is_dataclass(s): return {f.name: f.type for f in dataclasses.fields(s)} # type: ignore[misc] # ugh, why mypy thinks f.type can return str?? diff --git a/my/core/preinit.py b/my/core/preinit.py index be5477b..eb3a34f 100644 --- a/my/core/preinit.py +++ b/my/core/preinit.py @@ -8,6 +8,7 @@ def get_mycfg_dir() -> Path: import os import appdirs # type: ignore[import-untyped] + # not sure if that's necessary, i.e. could rely on PYTHONPATH instead # on the other hand, by using MY_CONFIG we are guaranteed to load it from the desired path? mvar = os.environ.get('MY_CONFIG') diff --git a/my/core/pytest.py b/my/core/pytest.py index e514957..ad9e7d7 100644 --- a/my/core/pytest.py +++ b/my/core/pytest.py @@ -2,7 +2,9 @@ Helpers to prevent depending on pytest in runtime """ -from .internal import assert_subpackage; assert_subpackage(__name__) +from .internal import assert_subpackage + +assert_subpackage(__name__) import sys import typing diff --git a/my/core/query.py b/my/core/query.py index 45806fb..50724a7 100644 --- a/my/core/query.py +++ b/my/core/query.py @@ -5,23 +5,20 @@ The main entrypoint to this library is the 'select' function below; try: python3 -c "from my.core.query import select; help(select)" """ +from __future__ import annotations + import dataclasses import importlib import inspect import itertools +from collections.abc import Iterable, Iterator from datetime import datetime from typing import ( Any, Callable, - Dict, - Iterable, - Iterator, - List, NamedTuple, Optional, - Tuple, TypeVar, - Union, ) import more_itertools @@ -51,6 +48,7 @@ class Unsortable(NamedTuple): class QueryException(ValueError): """Used to differentiate query-related errors, so the CLI interface is more expressive""" + pass @@ -63,7 +61,7 @@ def locate_function(module_name: str, function_name: str) -> Callable[[], Iterab """ try: mod = importlib.import_module(module_name) - for (fname, f) in inspect.getmembers(mod, inspect.isfunction): + for fname, f in inspect.getmembers(mod, inspect.isfunction): if fname == function_name: return f # in case the function is defined dynamically, @@ -83,10 +81,10 @@ def locate_qualified_function(qualified_name: str) -> Callable[[], Iterable[ET]] if "." not in qualified_name: raise QueryException("Could not find a '.' in the function name, e.g. my.reddit.rexport.comments") rdot_index = qualified_name.rindex(".") - return locate_function(qualified_name[:rdot_index], qualified_name[rdot_index + 1:]) + return locate_function(qualified_name[:rdot_index], qualified_name[rdot_index + 1 :]) -def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optional[OrderFunc]: +def attribute_func(obj: T, where: Where, default: U | None = None) -> OrderFunc | None: """ Attempts to find an attribute which matches the 'where_function' on the object, using some getattr/dict checks. Returns a function which when called with @@ -133,11 +131,11 @@ def attribute_func(obj: T, where: Where, default: Optional[U] = None) -> Optiona def _generate_order_by_func( obj_res: Res[T], *, - key: Optional[str] = None, - where_function: Optional[Where] = None, - default: Optional[U] = None, + key: str | None = None, + where_function: Where | None = None, + default: U | None = None, force_unsortable: bool = False, -) -> Optional[OrderFunc]: +) -> OrderFunc | None: """ Accepts an object Res[T] (Instance of some class or Exception) @@ -202,7 +200,7 @@ pass 'drop_exceptions' to ignore exceptions""") # user must provide either a key or a where predicate if where_function is not None: - func: Optional[OrderFunc] = attribute_func(obj, where_function, default) + func: OrderFunc | None = attribute_func(obj, where_function, default) if func is not None: return func @@ -218,8 +216,6 @@ pass 'drop_exceptions' to ignore exceptions""") return None # couldn't compute a OrderFunc for this class/instance - - # currently using the 'key set' as a proxy for 'this is the same type of thing' def _determine_order_by_value_key(obj_res: ET) -> Any: """ @@ -244,7 +240,7 @@ def _drop_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> Iterator[ET]: # try getting the first value from the iterator # similar to my.core.common.warn_if_empty? this doesn't go through the whole iterator though -def _peek_iter(itr: Iterator[ET]) -> Tuple[Optional[ET], Iterator[ET]]: +def _peek_iter(itr: Iterator[ET]) -> tuple[ET | None, Iterator[ET]]: itr = more_itertools.peekable(itr) try: first_item = itr.peek() @@ -255,9 +251,9 @@ def _peek_iter(itr: Iterator[ET]) -> Tuple[Optional[ET], Iterator[ET]]: # similar to 'my.core.error.sort_res_by'? -def _wrap_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> Tuple[Iterator[Unsortable], Iterator[ET]]: - unsortable: List[Unsortable] = [] - sortable: List[ET] = [] +def _wrap_unsorted(itr: Iterator[ET], orderfunc: OrderFunc) -> tuple[Iterator[Unsortable], Iterator[ET]]: + unsortable: list[Unsortable] = [] + sortable: list[ET] = [] for o in itr: # if input to select was another select if isinstance(o, Unsortable): @@ -279,7 +275,7 @@ def _handle_unsorted( orderfunc: OrderFunc, drop_unsorted: bool, wrap_unsorted: bool -) -> Tuple[Iterator[Unsortable], Iterator[ET]]: +) -> tuple[Iterator[Unsortable], Iterator[ET]]: # prefer drop_unsorted to wrap_unsorted, if both were present if drop_unsorted: return iter([]), _drop_unsorted(itr, orderfunc) @@ -294,16 +290,16 @@ def _handle_unsorted( # different types. ***This consumes the iterator***, so # you should definitely itertoolts.tee it beforehand # as to not exhaust the values -def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: Optional[U] = None) -> OrderFunc: +def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: U | None = None) -> OrderFunc: # TODO: add a kwarg to force lookup for every item? would sort of be like core.common.guess_datetime then - order_by_lookup: Dict[Any, OrderFunc] = {} + order_by_lookup: dict[Any, OrderFunc] = {} # need to go through a copy of the whole iterator here to # pre-generate functions to support sorting mixed types for obj_res in itr: key: Any = _determine_order_by_value_key(obj_res) if key not in order_by_lookup: - keyfunc: Optional[OrderFunc] = _generate_order_by_func( + keyfunc: OrderFunc | None = _generate_order_by_func( obj_res, where_function=order_value, default=default, @@ -324,12 +320,12 @@ def _generate_order_value_func(itr: Iterator[ET], order_value: Where, default: O def _handle_generate_order_by( itr, *, - order_by: Optional[OrderFunc] = None, - order_key: Optional[str] = None, - order_value: Optional[Where] = None, - default: Optional[U] = None, -) -> Tuple[Optional[OrderFunc], Iterator[ET]]: - order_by_chosen: Optional[OrderFunc] = order_by # if the user just supplied a function themselves + order_by: OrderFunc | None = None, + order_key: str | None = None, + order_value: Where | None = None, + default: U | None = None, +) -> tuple[OrderFunc | None, Iterator[ET]]: + order_by_chosen: OrderFunc | None = order_by # if the user just supplied a function themselves if order_by is not None: return order_by, itr if order_key is not None: @@ -354,19 +350,19 @@ def _handle_generate_order_by( def select( - src: Union[Iterable[ET], Callable[[], Iterable[ET]]], + src: Iterable[ET] | Callable[[], Iterable[ET]], *, - where: Optional[Where] = None, - order_by: Optional[OrderFunc] = None, - order_key: Optional[str] = None, - order_value: Optional[Where] = None, - default: Optional[U] = None, + where: Where | None = None, + order_by: OrderFunc | None = None, + order_key: str | None = None, + order_value: Where | None = None, + default: U | None = None, reverse: bool = False, - limit: Optional[int] = None, + limit: int | None = None, drop_unsorted: bool = False, wrap_unsorted: bool = True, warn_exceptions: bool = False, - warn_func: Optional[Callable[[Exception], None]] = None, + warn_func: Callable[[Exception], None] | None = None, drop_exceptions: bool = False, raise_exceptions: bool = False, ) -> Iterator[ET]: @@ -617,7 +613,7 @@ class _B(NamedTuple): # move these to tests/? They are re-used so much in the tests below, # not sure where the best place for these is -def _mixed_iter() -> Iterator[Union[_A, _B]]: +def _mixed_iter() -> Iterator[_A | _B]: yield _A(x=datetime(year=2009, month=5, day=10, hour=4, minute=10, second=1), y=5, z=10) yield _B(y=datetime(year=2015, month=5, day=10, hour=4, minute=10, second=1)) yield _A(x=datetime(year=2005, month=5, day=10, hour=4, minute=10, second=1), y=10, z=2) @@ -626,7 +622,7 @@ def _mixed_iter() -> Iterator[Union[_A, _B]]: yield _A(x=datetime(year=2005, month=4, day=10, hour=4, minute=10, second=1), y=2, z=-5) -def _mixed_iter_errors() -> Iterator[Res[Union[_A, _B]]]: +def _mixed_iter_errors() -> Iterator[Res[_A | _B]]: m = _mixed_iter() yield from itertools.islice(m, 0, 3) yield RuntimeError("Unhandled error!") diff --git a/my/core/query_range.py b/my/core/query_range.py index 1f4a7ff..2a8d7bd 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -7,11 +7,14 @@ filtered iterator See the select_range function below """ +from __future__ import annotations + import re import time +from collections.abc import Iterator from datetime import date, datetime, timedelta -from functools import lru_cache -from typing import Any, Callable, Iterator, NamedTuple, Optional, Type +from functools import cache +from typing import Any, Callable, NamedTuple import more_itertools @@ -25,7 +28,9 @@ from .query import ( select, ) -timedelta_regex = re.compile(r"^((?P[\.\d]+?)w)?((?P[\.\d]+?)d)?((?P[\.\d]+?)h)?((?P[\.\d]+?)m)?((?P[\.\d]+?)s)?$") +timedelta_regex = re.compile( + r"^((?P[\.\d]+?)w)?((?P[\.\d]+?)d)?((?P[\.\d]+?)h)?((?P[\.\d]+?)m)?((?P[\.\d]+?)s)?$" +) # https://stackoverflow.com/a/51916936 @@ -88,7 +93,7 @@ def parse_datetime_float(date_str: str) -> float: # dateparser is a bit more lenient than the above, lets you type # all sorts of dates as inputs # https://github.com/scrapinghub/dateparser#how-to-use - res: Optional[datetime] = dateparser.parse(ds, settings={"DATE_ORDER": "YMD"}) + res: datetime | None = dateparser.parse(ds, settings={"DATE_ORDER": "YMD"}) if res is not None: return res.timestamp() @@ -98,7 +103,7 @@ def parse_datetime_float(date_str: str) -> float: # probably DateLike input? but a user could specify an order_key # which is an epoch timestamp or a float value which they # expect to be converted to a datetime to compare -@lru_cache(maxsize=None) +@cache def _datelike_to_float(dl: Any) -> float: if isinstance(dl, datetime): return dl.timestamp() @@ -130,11 +135,12 @@ class RangeTuple(NamedTuple): of the timeframe -- 'before' - before and after - anything after 'after' and before 'before', acts as a time range """ + # technically doesn't need to be Optional[Any], # just to make it more clear these can be None - after: Optional[Any] - before: Optional[Any] - within: Optional[Any] + after: Any | None + before: Any | None + within: Any | None Converter = Callable[[Any], Any] @@ -145,9 +151,9 @@ def _parse_range( unparsed_range: RangeTuple, end_parser: Converter, within_parser: Converter, - parsed_range: Optional[RangeTuple] = None, - error_message: Optional[str] = None -) -> Optional[RangeTuple]: + parsed_range: RangeTuple | None = None, + error_message: str | None = None, +) -> RangeTuple | None: if parsed_range is not None: return parsed_range @@ -176,11 +182,11 @@ def _create_range_filter( end_parser: Converter, within_parser: Converter, attr_func: Where, - parsed_range: Optional[RangeTuple] = None, - default_before: Optional[Any] = None, - value_coercion_func: Optional[Converter] = None, - error_message: Optional[str] = None, -) -> Optional[Where]: + parsed_range: RangeTuple | None = None, + default_before: Any | None = None, + value_coercion_func: Converter | None = None, + error_message: str | None = None, +) -> Where | None: """ Handles: - parsing the user input into values that are comparable to items the iterable returns @@ -272,17 +278,17 @@ def _create_range_filter( def select_range( itr: Iterator[ET], *, - where: Optional[Where] = None, - order_key: Optional[str] = None, - order_value: Optional[Where] = None, - order_by_value_type: Optional[Type] = None, - unparsed_range: Optional[RangeTuple] = None, + where: Where | None = None, + order_key: str | None = None, + order_value: Where | None = None, + order_by_value_type: type | None = None, + unparsed_range: RangeTuple | None = None, reverse: bool = False, - limit: Optional[int] = None, + limit: int | None = None, drop_unsorted: bool = False, wrap_unsorted: bool = False, warn_exceptions: bool = False, - warn_func: Optional[Callable[[Exception], None]] = None, + warn_func: Callable[[Exception], None] | None = None, drop_exceptions: bool = False, raise_exceptions: bool = False, ) -> Iterator[ET]: @@ -317,9 +323,10 @@ def select_range( drop_exceptions=drop_exceptions, raise_exceptions=raise_exceptions, warn_exceptions=warn_exceptions, - warn_func=warn_func) + warn_func=warn_func, + ) - order_by_chosen: Optional[OrderFunc] = None + order_by_chosen: OrderFunc | None = None # if the user didn't specify an attribute to order value, but specified a type # we should search for on each value in the iterator @@ -345,7 +352,7 @@ Specify a type or a key to order the value by""") # force drop_unsorted=True so we can use _create_range_filter # sort the iterable by the generated order_by_chosen function itr = select(itr, order_by=order_by_chosen, drop_unsorted=True) - filter_func: Optional[Where] + filter_func: Where | None if order_by_value_type in [datetime, date]: filter_func = _create_range_filter( unparsed_range=unparsed_range, @@ -353,7 +360,8 @@ Specify a type or a key to order the value by""") within_parser=parse_timedelta_float, attr_func=order_by_chosen, # type: ignore[arg-type] default_before=time.time(), - value_coercion_func=_datelike_to_float) + value_coercion_func=_datelike_to_float, + ) elif order_by_value_type in [int, float]: # allow primitives to be converted using the default int(), float() callables filter_func = _create_range_filter( @@ -362,7 +370,8 @@ Specify a type or a key to order the value by""") within_parser=order_by_value_type, attr_func=order_by_chosen, # type: ignore[arg-type] default_before=None, - value_coercion_func=order_by_value_type) + value_coercion_func=order_by_value_type, + ) else: # TODO: add additional kwargs to let the user sort by other values, by specifying the parsers? # would need to allow passing the end_parser, within parser, default before and value_coercion_func... @@ -470,7 +479,7 @@ def test_range_predicate() -> None: # filter from 0 to 5 rn: RangeTuple = RangeTuple("0", "5", None) - zero_to_five_filter: Optional[Where] = int_filter_func(unparsed_range=rn) + zero_to_five_filter: Where | None = int_filter_func(unparsed_range=rn) assert zero_to_five_filter is not None # this is just a Where function, given some input it return True/False if the value is allowed assert zero_to_five_filter(3) is True @@ -483,6 +492,7 @@ def test_range_predicate() -> None: rn = RangeTuple(None, 3, "3.5") assert list(filter(int_filter_func(unparsed_range=rn, attr_func=identity), src())) == ["0", "1", "2"] + def test_parse_range() -> None: from functools import partial diff --git a/my/core/serialize.py b/my/core/serialize.py index ab11a20..e36da8f 100644 --- a/my/core/serialize.py +++ b/my/core/serialize.py @@ -1,9 +1,11 @@ +from __future__ import annotations + import datetime from dataclasses import asdict, is_dataclass from decimal import Decimal -from functools import lru_cache +from functools import cache from pathlib import Path -from typing import Any, Callable, NamedTuple, Optional +from typing import Any, Callable, NamedTuple from .error import error_to_json from .pytest import parametrize @@ -57,12 +59,12 @@ def _default_encode(obj: Any) -> Any: # could possibly run multiple times/raise warning if you provide different 'default' # functions or change the kwargs? The alternative is to maintain all of this at the module # level, which is just as annoying -@lru_cache(maxsize=None) +@cache def _dumps_factory(**kwargs) -> Callable[[Any], str]: use_default: DefaultEncoder = _default_encode # if the user passed an additional 'default' parameter, # try using that to serialize before before _default_encode - _additional_default: Optional[DefaultEncoder] = kwargs.get("default") + _additional_default: DefaultEncoder | None = kwargs.get("default") if _additional_default is not None and callable(_additional_default): def wrapped_default(obj: Any) -> Any: @@ -78,9 +80,9 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: kwargs["default"] = use_default - prefer_factory: Optional[str] = kwargs.pop('_prefer_factory', None) + prefer_factory: str | None = kwargs.pop('_prefer_factory', None) - def orjson_factory() -> Optional[Dumps]: + def orjson_factory() -> Dumps | None: try: import orjson except ModuleNotFoundError: @@ -95,7 +97,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: return _orjson_dumps - def simplejson_factory() -> Optional[Dumps]: + def simplejson_factory() -> Dumps | None: try: from simplejson import dumps as simplejson_dumps except ModuleNotFoundError: @@ -115,7 +117,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: return _simplejson_dumps - def stdlib_factory() -> Optional[Dumps]: + def stdlib_factory() -> Dumps | None: import json from .warnings import high @@ -150,7 +152,7 @@ def _dumps_factory(**kwargs) -> Callable[[Any], str]: def dumps( obj: Any, - default: Optional[DefaultEncoder] = None, + default: DefaultEncoder | None = None, **kwargs, ) -> str: """ diff --git a/my/core/source.py b/my/core/source.py index 52c58c1..a309d13 100644 --- a/my/core/source.py +++ b/my/core/source.py @@ -3,9 +3,12 @@ Decorator to gracefully handle importing a data source, or warning and yielding nothing (or a default) when its not available """ +from __future__ import annotations + import warnings +from collections.abc import Iterable, Iterator from functools import wraps -from typing import Any, Callable, Iterable, Iterator, Optional, TypeVar +from typing import Any, Callable, TypeVar from .warnings import medium @@ -26,8 +29,8 @@ _DEFAULT_ITR = () def import_source( *, default: Iterable[T] = _DEFAULT_ITR, - module_name: Optional[str] = None, - help_url: Optional[str] = None, + module_name: str | None = None, + help_url: str | None = None, ) -> Callable[..., Callable[..., Iterator[T]]]: """ doesn't really play well with types, but is used to catch @@ -50,6 +53,7 @@ def import_source( except (ImportError, AttributeError) as err: from . import core_config as CC from .error import warn_my_config_import_error + suppressed_in_conf = False if module_name is not None and CC.config._is_module_active(module_name) is False: suppressed_in_conf = True @@ -72,5 +76,7 @@ class core: if not matched_config_err and isinstance(err, AttributeError): raise err yield from default + return wrapper + return decorator diff --git a/my/core/sqlite.py b/my/core/sqlite.py index 08a80e5..aa41ab3 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -1,12 +1,16 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations +from .internal import assert_subpackage # noqa: I001 + +assert_subpackage(__name__) import shutil import sqlite3 +from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from tempfile import TemporaryDirectory -from typing import Any, Callable, Iterator, Literal, Optional, Tuple, Union, overload +from typing import Any, Callable, Literal, Union, overload from .common import PathIsh from .compat import assert_never @@ -22,6 +26,7 @@ def test_sqlite_connect_immutable(tmp_path: Path) -> None: conn.execute('CREATE TABLE testtable (col)') import pytest + with pytest.raises(sqlite3.OperationalError, match='readonly database'): with sqlite_connect_immutable(db) as conn: conn.execute('DROP TABLE testtable') @@ -33,6 +38,7 @@ def test_sqlite_connect_immutable(tmp_path: Path) -> None: SqliteRowFactory = Callable[[sqlite3.Cursor, sqlite3.Row], Any] + def dict_factory(cursor, row): fields = [column[0] for column in cursor.description] return dict(zip(fields, row)) @@ -40,8 +46,9 @@ def dict_factory(cursor, row): Factory = Union[SqliteRowFactory, Literal['row', 'dict']] + @contextmanager -def sqlite_connection(db: PathIsh, *, immutable: bool=False, row_factory: Optional[Factory]=None) -> Iterator[sqlite3.Connection]: +def sqlite_connection(db: PathIsh, *, immutable: bool = False, row_factory: Factory | None = None) -> Iterator[sqlite3.Connection]: dbp = f'file:{db}' # https://www.sqlite.org/draft/uri.html#uriimmutable if immutable: @@ -97,30 +104,32 @@ def sqlite_copy_and_open(db: PathIsh) -> sqlite3.Connection: # and then the return type ends up as Iterator[Tuple[str, ...]], which isn't desirable :( # a bit annoying to have this copy-pasting, but hopefully not a big issue +# fmt: off @overload -def select(cols: Tuple[str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any ]]: ... +def select(cols: tuple[str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any ]]: ... @overload -def select(cols: Tuple[str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any ]]: ... +def select(cols: tuple[str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any, Any, Any ]]: ... +def select(cols: tuple[str, str, str, str, str, str, str ], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any, Any, Any ]]: ... @overload -def select(cols: Tuple[str, str, str, str, str, str, str, str], rest: str, *, db: sqlite3.Connection) -> \ - Iterator[Tuple[Any, Any, Any, Any, Any, Any, Any, Any]]: ... +def select(cols: tuple[str, str, str, str, str, str, str, str], rest: str, *, db: sqlite3.Connection) -> \ + Iterator[tuple[Any, Any, Any, Any, Any, Any, Any, Any]]: ... +# fmt: on def select(cols, rest, *, db): # db arg is last cause that results in nicer code formatting.. diff --git a/my/core/stats.py b/my/core/stats.py index 674a8d1..a553db3 100644 --- a/my/core/stats.py +++ b/my/core/stats.py @@ -2,10 +2,13 @@ Helpers for hpi doctor/stats functionality. ''' +from __future__ import annotations + import collections.abc import importlib import inspect import typing +from collections.abc import Iterable, Iterator, Sequence from contextlib import contextmanager from datetime import datetime from pathlib import Path @@ -13,20 +16,13 @@ from types import ModuleType from typing import ( Any, Callable, - Dict, - Iterable, - Iterator, - List, - Optional, Protocol, - Sequence, - Union, cast, ) from .types import asdict -Stats = Dict[str, Any] +Stats = dict[str, Any] class StatsFun(Protocol): @@ -55,10 +51,10 @@ def quick_stats(): def stat( - func: Union[Callable[[], Iterable[Any]], Iterable[Any]], + func: Callable[[], Iterable[Any]] | Iterable[Any], *, quick: bool = False, - name: Optional[str] = None, + name: str | None = None, ) -> Stats: """ Extracts various statistics from a passed iterable/callable, e.g.: @@ -153,8 +149,8 @@ def test_stat() -> None: # -def get_stats(module_name: str, *, guess: bool = False) -> Optional[StatsFun]: - stats: Optional[StatsFun] = None +def get_stats(module_name: str, *, guess: bool = False) -> StatsFun | None: + stats: StatsFun | None = None try: module = importlib.import_module(module_name) except Exception: @@ -167,7 +163,7 @@ def get_stats(module_name: str, *, guess: bool = False) -> Optional[StatsFun]: # TODO maybe could be enough to annotate OUTPUTS or something like that? # then stats could just use them as hints? -def guess_stats(module: ModuleType) -> Optional[StatsFun]: +def guess_stats(module: ModuleType) -> StatsFun | None: """ If the module doesn't have explicitly defined 'stat' function, this is used to try to guess what could be included in stats automatically @@ -206,7 +202,7 @@ def test_guess_stats() -> None: } -def _guess_data_providers(module: ModuleType) -> Dict[str, Callable]: +def _guess_data_providers(module: ModuleType) -> dict[str, Callable]: mfunctions = inspect.getmembers(module, inspect.isfunction) return {k: v for k, v in mfunctions if is_data_provider(v)} @@ -263,7 +259,7 @@ def test_is_data_provider() -> None: lam = lambda: [1, 2] assert not idp(lam) - def has_extra_args(count) -> List[int]: + def has_extra_args(count) -> list[int]: return list(range(count)) assert not idp(has_extra_args) @@ -340,10 +336,10 @@ def test_type_is_iterable() -> None: assert not fun(None) assert not fun(int) assert not fun(Any) - assert not fun(Dict[int, int]) + assert not fun(dict[int, int]) - assert fun(List[int]) - assert fun(Sequence[Dict[str, str]]) + assert fun(list[int]) + assert fun(Sequence[dict[str, str]]) assert fun(Iterable[Any]) @@ -434,7 +430,7 @@ def test_stat_iterable() -> None: # experimental, not sure about it.. -def _guess_datetime(x: Any) -> Optional[datetime]: +def _guess_datetime(x: Any) -> datetime | None: # todo hmm implement without exception.. try: d = asdict(x) diff --git a/my/core/structure.py b/my/core/structure.py index fa26532..bb049e4 100644 --- a/my/core/structure.py +++ b/my/core/structure.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import atexit import os import shutil @@ -5,9 +7,9 @@ import sys import tarfile import tempfile import zipfile +from collections.abc import Generator, Sequence from contextlib import contextmanager from pathlib import Path -from typing import Generator, List, Sequence, Tuple, Union from .logging import make_logger @@ -42,10 +44,10 @@ TARGZ_EXT = {".tar.gz"} @contextmanager def match_structure( base: Path, - expected: Union[str, Sequence[str]], + expected: str | Sequence[str], *, partial: bool = False, -) -> Generator[Tuple[Path, ...], None, None]: +) -> Generator[tuple[Path, ...], None, None]: """ Given a 'base' directory or archive (zip/tar.gz), recursively search for one or more paths that match the pattern described in 'expected'. That can be a single string, or a list @@ -140,8 +142,8 @@ def match_structure( if not searchdir.is_dir(): raise NotADirectoryError(f"Expected either a zip/tar.gz archive or a directory, received {searchdir}") - matches: List[Path] = [] - possible_targets: List[Path] = [searchdir] + matches: list[Path] = [] + possible_targets: list[Path] = [searchdir] while len(possible_targets) > 0: p = possible_targets.pop(0) @@ -172,7 +174,7 @@ def warn_leftover_files() -> None: from . import core_config as CC base_tmp: Path = CC.config.get_tmp_dir() - leftover: List[Path] = list(base_tmp.iterdir()) + leftover: list[Path] = list(base_tmp.iterdir()) if leftover: logger.debug(f"at exit warning: Found leftover files in temporary directory '{leftover}'. this may be because you have multiple hpi processes running -- if so this can be ignored") diff --git a/my/core/tests/auto_stats.py b/my/core/tests/auto_stats.py index d10d4c4..fc49e03 100644 --- a/my/core/tests/auto_stats.py +++ b/my/core/tests/auto_stats.py @@ -2,11 +2,11 @@ Helper 'module' for test_guess_stats """ +from collections.abc import Iterable, Iterator, Sequence from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path -from typing import Iterable, Iterator, Sequence @dataclass diff --git a/my/core/tests/common.py b/my/core/tests/common.py index 22a74d7..073ea5f 100644 --- a/my/core/tests/common.py +++ b/my/core/tests/common.py @@ -1,6 +1,8 @@ +from __future__ import annotations + import os +from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterator, Optional import pytest @@ -15,7 +17,7 @@ skip_if_uses_optional_deps = pytest.mark.skipif( # TODO maybe move to hpi core? @contextmanager -def tmp_environ_set(key: str, value: Optional[str]) -> Iterator[None]: +def tmp_environ_set(key: str, value: str | None) -> Iterator[None]: prev_value = os.environ.get(key) if value is None: os.environ.pop(key, None) diff --git a/my/core/tests/denylist.py b/my/core/tests/denylist.py index 2688319..73c3165 100644 --- a/my/core/tests/denylist.py +++ b/my/core/tests/denylist.py @@ -1,8 +1,9 @@ import json import warnings +from collections.abc import Iterator from datetime import datetime from pathlib import Path -from typing import Iterator, NamedTuple +from typing import NamedTuple from ..denylist import DenyList diff --git a/my/core/tests/test_cachew.py b/my/core/tests/test_cachew.py index 70ac76f..a0d2267 100644 --- a/my/core/tests/test_cachew.py +++ b/my/core/tests/test_cachew.py @@ -1,6 +1,6 @@ -from .common import skip_if_uses_optional_deps as pytestmark +from __future__ import annotations -from typing import List +from .common import skip_if_uses_optional_deps as pytestmark # TODO ugh, this is very messy.. need to sort out config overriding here @@ -16,7 +16,7 @@ def test_cachew() -> None: # TODO ugh. need doublewrap or something to avoid having to pass parens @mcachew() - def cf() -> List[int]: + def cf() -> list[int]: nonlocal called called += 1 return [1, 2, 3] @@ -43,7 +43,7 @@ def test_cachew_dir_none() -> None: called = 0 @mcachew(cache_path=cache_dir() / 'ctest') - def cf() -> List[int]: + def cf() -> list[int]: nonlocal called called += 1 return [called, called, called] diff --git a/my/core/tests/test_config.py b/my/core/tests/test_config.py index 78d1a62..f6d12ba 100644 --- a/my/core/tests/test_config.py +++ b/my/core/tests/test_config.py @@ -2,8 +2,8 @@ Various tests that are checking behaviour of user config wrt to various things """ -import sys import os +import sys from pathlib import Path import pytest diff --git a/my/core/time.py b/my/core/time.py index fa20a7c..a9b180d 100644 --- a/my/core/time.py +++ b/my/core/time.py @@ -1,5 +1,7 @@ -from functools import lru_cache -from typing import Dict, Sequence +from __future__ import annotations + +from collections.abc import Sequence +from functools import cache, lru_cache import pytz @@ -11,6 +13,7 @@ def user_forced() -> Sequence[str]: # https://stackoverflow.com/questions/36067621/python-all-possible-timezone-abbreviations-for-given-timezone-name-and-vise-ve try: from my.config import time as user_config + return user_config.tz.force_abbreviations # type: ignore[attr-defined] # noqa: TRY300 # note: noqa since we're catching case where config doesn't have attribute here as well except: @@ -19,15 +22,15 @@ def user_forced() -> Sequence[str]: @lru_cache(1) -def _abbr_to_timezone_map() -> Dict[str, pytz.BaseTzInfo]: +def _abbr_to_timezone_map() -> dict[str, pytz.BaseTzInfo]: # also force UTC to always correspond to utc # this makes more sense than Zulu it ends up by default timezones = [*pytz.all_timezones, 'UTC', *user_forced()] - res: Dict[str, pytz.BaseTzInfo] = {} + res: dict[str, pytz.BaseTzInfo] = {} for tzname in timezones: tz = pytz.timezone(tzname) - infos = getattr(tz, '_tzinfos', []) # not sure if can rely on attr always present? + infos = getattr(tz, '_tzinfos', []) # not sure if can rely on attr always present? for info in infos: abbr = info[-1] # todo could support this with a better error handling strategy? @@ -43,7 +46,7 @@ def _abbr_to_timezone_map() -> Dict[str, pytz.BaseTzInfo]: return res -@lru_cache(maxsize=None) +@cache def abbr_to_timezone(abbr: str) -> pytz.BaseTzInfo: return _abbr_to_timezone_map()[abbr] diff --git a/my/core/types.py b/my/core/types.py index b1cf103..dc19c19 100644 --- a/my/core/types.py +++ b/my/core/types.py @@ -1,14 +1,15 @@ -from .internal import assert_subpackage; assert_subpackage(__name__) +from __future__ import annotations + +from .internal import assert_subpackage + +assert_subpackage(__name__) from dataclasses import asdict as dataclasses_asdict from dataclasses import is_dataclass from datetime import datetime -from typing import ( - Any, - Dict, -) +from typing import Any -Json = Dict[str, Any] +Json = dict[str, Any] # for now just serves documentation purposes... but one day might make it statically verifiable where possible? diff --git a/my/core/util.py b/my/core/util.py index a247f81..74e71e1 100644 --- a/my/core/util.py +++ b/my/core/util.py @@ -1,10 +1,12 @@ +from __future__ import annotations + import os import pkgutil import sys +from collections.abc import Iterable from itertools import chain from pathlib import Path from types import ModuleType -from typing import Iterable, List, Optional from .discovery_pure import HPIModule, _is_not_module_src, has_stats, ignored @@ -20,13 +22,14 @@ from .discovery_pure import NOT_HPI_MODULE_VAR assert NOT_HPI_MODULE_VAR in globals() # check name consistency -def is_not_hpi_module(module: str) -> Optional[str]: + +def is_not_hpi_module(module: str) -> str | None: ''' None if a module, otherwise returns reason ''' import importlib.util - path: Optional[str] = None + path: str | None = None try: # TODO annoying, this can cause import of the parent module? spec = importlib.util.find_spec(module) @@ -35,7 +38,7 @@ def is_not_hpi_module(module: str) -> Optional[str]: except Exception as e: # 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? + assert path is not None # not sure if can happen? if _is_not_module_src(Path(path)): return f"marked explicitly (via {NOT_HPI_MODULE_VAR})" @@ -57,9 +60,10 @@ def _iter_all_importables(pkg: ModuleType) -> Iterable[HPIModule]: def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModule]: - from .core_config import config - """Yield all importables under a given path and package.""" + + from .core_config import config # noqa: F401 + for dir_path, dirs, file_names in os.walk(pkg_pth): file_names.sort() # NOTE: sorting dirs in place is intended, it's the way you're supposed to do it with os.walk @@ -82,6 +86,7 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu # TODO might need to make it defensive and yield Exception (otherwise hpi doctor might fail for no good reason) # use onerror=? + # ignored explicitly -> not HPI # if enabled in config -> HPI # if disabled in config -> HPI @@ -90,7 +95,7 @@ def _discover_path_importables(pkg_pth: Path, pkg_name: str) -> Iterable[HPIModu # TODO when do we need to recurse? -def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterable[HPIModule]: +def _walk_packages(path: Iterable[str], prefix: str = '', onerror=None) -> Iterable[HPIModule]: """ Modified version of https://github.com/python/cpython/blob/d50a0700265536a20bcce3fb108c954746d97625/Lib/pkgutil.py#L53, to avoid importing modules that are skipped @@ -153,8 +158,9 @@ def _walk_packages(path: Iterable[str], prefix: str='', onerror=None) -> Iterabl path = [p for p in path if not seen(p)] yield from _walk_packages(path, mname + '.', onerror) + # deprecate? -def get_modules() -> List[HPIModule]: +def get_modules() -> list[HPIModule]: return list(modules()) @@ -169,14 +175,14 @@ def test_module_detection() -> None: with reset() as cc: cc.disabled_modules = ['my.location.*', 'my.body.*', 'my.workouts.*', 'my.private.*'] mods = {m.name: m for m in modules()} - assert mods['my.demo'] .skip_reason == "has no 'stats()' function" + assert mods['my.demo'].skip_reason == "has no 'stats()' function" with reset() as cc: cc.disabled_modules = ['my.location.*', 'my.body.*', 'my.workouts.*', 'my.private.*', 'my.lastfm'] - cc.enabled_modules = ['my.demo'] + cc.enabled_modules = ['my.demo'] mods = {m.name: m for m in modules()} - assert mods['my.demo'] .skip_reason is None # not skipped + assert mods['my.demo'].skip_reason is None # not skipped assert mods['my.lastfm'].skip_reason == "suppressed in the user config" diff --git a/my/core/utils/concurrent.py b/my/core/utils/concurrent.py index 73944ec..515c3f1 100644 --- a/my/core/utils/concurrent.py +++ b/my/core/utils/concurrent.py @@ -1,6 +1,7 @@ -import sys +from __future__ import annotations + from concurrent.futures import Executor, Future -from typing import Any, Callable, Optional, TypeVar +from typing import Any, Callable, TypeVar from ..compat import ParamSpec @@ -15,7 +16,7 @@ class DummyExecutor(Executor): but also want to provide an option to run the code serially (e.g. for debugging) """ - def __init__(self, max_workers: Optional[int] = 1) -> None: + def __init__(self, max_workers: int | None = 1) -> None: self._shutdown = False self._max_workers = max_workers diff --git a/my/core/utils/imports.py b/my/core/utils/imports.py index 4666a5e..e0fb01d 100644 --- a/my/core/utils/imports.py +++ b/my/core/utils/imports.py @@ -1,27 +1,27 @@ +from __future__ import annotations + import importlib import importlib.util import sys from pathlib import Path from types import ModuleType -from typing import Optional - -from ..common import PathIsh # TODO only used in tests? not sure if useful at all. -def import_file(p: PathIsh, name: Optional[str] = None) -> ModuleType: +def import_file(p: Path | str, name: str | None = None) -> ModuleType: p = Path(p) if name is None: name = p.stem spec = importlib.util.spec_from_file_location(name, p) assert spec is not None, f"Fatal error; Could not create module spec from {name} {p}" foo = importlib.util.module_from_spec(spec) - loader = spec.loader; assert loader is not None + loader = spec.loader + assert loader is not None loader.exec_module(foo) return foo -def import_from(path: PathIsh, name: str) -> ModuleType: +def import_from(path: Path | str, name: str) -> ModuleType: path = str(path) sys.path.append(path) try: @@ -30,7 +30,7 @@ def import_from(path: PathIsh, name: str) -> ModuleType: sys.path.remove(path) -def import_dir(path: PathIsh, extra: str = '') -> ModuleType: +def import_dir(path: Path | str, extra: str = '') -> ModuleType: p = Path(path) if p.parts[0] == '~': p = p.expanduser() # TODO eh. not sure about this.. diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index ae9402d..501ebbe 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -4,17 +4,13 @@ Various helpers/transforms of iterators Ideally this should be as small as possible and we should rely on stdlib itertools or more_itertools """ +from __future__ import annotations + import warnings -from collections.abc import Hashable +from collections.abc import Hashable, Iterable, Iterator, Sized from typing import ( TYPE_CHECKING, Callable, - Dict, - Iterable, - Iterator, - List, - Optional, - Sized, TypeVar, Union, cast, @@ -23,9 +19,8 @@ from typing import ( import more_itertools from decorator import decorator -from ..compat import ParamSpec from .. import warnings as core_warnings - +from ..compat import ParamSpec T = TypeVar('T') K = TypeVar('K') @@ -39,7 +34,7 @@ def _identity(v: T) -> V: # type: ignore[type-var] # ugh. nothing in more_itertools? # perhaps duplicates_everseen? but it doesn't yield non-unique elements? def ensure_unique(it: Iterable[T], *, key: Callable[[T], K]) -> Iterable[T]: - key2item: Dict[K, T] = {} + key2item: dict[K, T] = {} for i in it: k = key(i) pi = key2item.get(k, None) @@ -72,10 +67,10 @@ def make_dict( key: Callable[[T], K], # TODO make value optional instead? but then will need a typing override for it? value: Callable[[T], V] = _identity, -) -> Dict[K, V]: +) -> dict[K, V]: with_keys = ((key(i), i) for i in it) uniques = ensure_unique(with_keys, key=lambda p: p[0]) - res: Dict[K, V] = {} + res: dict[K, V] = {} for k, i in uniques: res[k] = i if value is None else value(i) return res @@ -93,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') @@ -102,7 +97,7 @@ LV = TypeVar('LV') @decorator -def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.kwargs) -> List[LV]: +def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.kwargs) -> list[LV]: """ Wraps a function's return value in wrapper (e.g. list) Useful when an algorithm can be expressed more cleanly as a generator @@ -115,7 +110,7 @@ def _listify(func: Callable[LFP, Iterable[LV]], *args: LFP.args, **kwargs: LFP.k # so seems easiest to just use specialize instantiations of decorator instead if TYPE_CHECKING: - def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, List[LV]]: ... # noqa: ARG001 + def listify(func: Callable[LFP, Iterable[LV]]) -> Callable[LFP, list[LV]]: ... # noqa: ARG001 else: listify = _listify @@ -130,7 +125,7 @@ def test_listify() -> None: yield 2 res = it() - assert_type(res, List[int]) + assert_type(res, list[int]) assert res == [1, 2] @@ -201,24 +196,24 @@ def test_warn_if_empty_list() -> None: ll = [1, 2, 3] @warn_if_empty - def nonempty() -> List[int]: + def nonempty() -> list[int]: return ll with warnings.catch_warnings(record=True) as w: res1 = nonempty() assert len(w) == 0 - assert_type(res1, List[int]) + assert_type(res1, list[int]) assert isinstance(res1, list) assert res1 is ll # object should be unchanged! @warn_if_empty - def empty() -> List[str]: + def empty() -> list[str]: return [] with warnings.catch_warnings(record=True) as w: res2 = empty() assert len(w) == 1 - assert_type(res2, List[str]) + assert_type(res2, list[str]) assert isinstance(res2, list) assert res2 == [] @@ -242,7 +237,7 @@ def check_if_hashable(iterable: Iterable[_HT]) -> Iterable[_HT]: """ NOTE: Despite Hashable bound, typing annotation doesn't guarantee runtime safety Consider hashable type X, and Y that inherits from X, but not hashable - Then l: List[X] = [Y(...)] is a valid expression, and type checks against Hashable, + Then l: list[X] = [Y(...)] is a valid expression, and type checks against Hashable, but isn't runtime hashable """ # Sadly this doesn't work 100% correctly with dataclasses atm... @@ -268,28 +263,27 @@ def check_if_hashable(iterable: Iterable[_HT]) -> Iterable[_HT]: # TODO different policies -- error/warn/ignore? def test_check_if_hashable() -> None: from dataclasses import dataclass - from typing import Set, Tuple import pytest from ..compat import assert_type - x1: List[int] = [1, 2] + x1: list[int] = [1, 2] r1 = check_if_hashable(x1) assert_type(r1, Iterable[int]) assert r1 is x1 - x2: Iterator[Union[int, str]] = iter((123, 'aba')) + x2: Iterator[int | str] = iter((123, 'aba')) r2 = check_if_hashable(x2) assert_type(r2, Iterable[Union[int, str]]) assert list(r2) == [123, 'aba'] - x3: Tuple[object, ...] = (789, 'aba') + x3: tuple[object, ...] = (789, 'aba') r3 = check_if_hashable(x3) assert_type(r3, Iterable[object]) assert r3 is x3 # object should be unchanged - x4: List[Set[int]] = [{1, 2, 3}, {4, 5, 6}] + 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] @@ -307,7 +301,7 @@ def test_check_if_hashable() -> None: class X: a: int - x6: List[X] = [X(a=123)] + x6: list[X] = [X(a=123)] r6 = check_if_hashable(x6) assert x6 is r6 @@ -316,7 +310,7 @@ def test_check_if_hashable() -> None: class Y(X): b: str - x7: List[Y] = [Y(a=123, b='aba')] + x7: list[Y] = [Y(a=123, b='aba')] with pytest.raises(Exception): # ideally that would also be rejected by mypy, but currently there is a bug # which treats all dataclasses as hashable: https://github.com/python/mypy/issues/11463 @@ -331,11 +325,8 @@ _UEU = TypeVar('_UEU') # instead of just iterator # TODO maybe deprecated Callable support? not sure def unique_everseen( - fun: Union[ - Callable[[], Iterable[_UET]], - Iterable[_UET] - ], - key: Optional[Callable[[_UET], _UEU]] = None, + fun: Callable[[], Iterable[_UET]] | Iterable[_UET], + key: Callable[[_UET], _UEU] | None = None, ) -> Iterator[_UET]: import os diff --git a/my/core/warnings.py b/my/core/warnings.py index 2ffc3e4..d67ec7d 100644 --- a/my/core/warnings.py +++ b/my/core/warnings.py @@ -5,14 +5,16 @@ since who looks at the terminal output? E.g. would be nice to propagate the warnings in the UI (it's even a subclass of Exception!) ''' +from __future__ import annotations + import sys import warnings -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING import click -def _colorize(x: str, color: Optional[str] = None) -> str: +def _colorize(x: str, color: str | None = None) -> str: if color is None: return x @@ -24,7 +26,7 @@ def _colorize(x: str, color: Optional[str] = None) -> str: return click.style(x, fg=color) -def _warn(message: str, *args, color: Optional[str] = None, **kwargs) -> None: +def _warn(message: str, *args, color: str | None = None, **kwargs) -> None: stacklevel = kwargs.get('stacklevel', 1) kwargs['stacklevel'] = stacklevel + 2 # +1 for this function, +1 for medium/high wrapper warnings.warn(_colorize(message, color=color), *args, **kwargs) # noqa: B028 From 8496d131e7e44b3effcc289762a4218aa1457725 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sat, 19 Oct 2024 22:10:40 +0100 Subject: [PATCH 46/55] general: migrate modules to use 3.9 features --- my/arbtt.py | 23 +++++++----- my/bluemaestro.py | 11 +++--- my/body/blood.py | 36 ++++++++++--------- my/body/exercise/all.py | 6 ++-- my/body/exercise/cardio.py | 1 - my/body/exercise/cross_trainer.py | 18 ++++++---- my/body/sleep/common.py | 5 +-- my/body/sleep/main.py | 5 ++- my/body/weight.py | 8 ++--- my/books/kobo.py | 7 ++-- my/browser/active_browser.py | 8 +++-- my/browser/all.py | 6 ++-- my/browser/export.py | 9 ++--- my/bumble/android.py | 26 +++++++------- my/calendar/holidays.py | 3 +- my/cfg.py | 1 - my/codeforces.py | 9 +++-- my/coding/commits.py | 34 +++++++++--------- my/common.py | 2 +- my/config.py | 36 ++++++++++--------- my/core/_deprecated/kompress.py | 2 +- my/core/common.py | 4 +-- my/demo.py | 6 ++-- my/emfit/__init__.py | 46 +++++++++++++----------- my/endomondo.py | 24 ++++++++----- my/error.py | 2 +- my/experimental/destructive_parsing.py | 9 ++--- my/fbmessenger/__init__.py | 1 + my/fbmessenger/all.py | 6 ++-- my/fbmessenger/android.py | 35 ++++++++++--------- my/fbmessenger/common.py | 18 ++++++---- my/fbmessenger/export.py | 9 +++-- my/foursquare.py | 9 +++-- my/github/all.py | 3 +- my/github/common.py | 21 ++++++----- my/github/gdpr.py | 3 +- my/github/ghexport.py | 25 +++++++++----- my/goodreads.py | 16 +++++---- my/google/maps/_android_protobuf.py | 4 +-- my/google/maps/android.py | 12 +++---- my/google/takeout/html.py | 28 ++++++++------- my/google/takeout/parser.py | 20 ++++++----- my/google/takeout/paths.py | 12 ++++--- my/hackernews/dogsheep.py | 12 +++---- my/hackernews/harmonic.py | 25 +++++++++----- my/hackernews/materialistic.py | 11 +++--- my/hypothesis.py | 10 +++--- my/instagram/all.py | 5 ++- my/instagram/android.py | 37 ++++++++++---------- my/instagram/common.py | 9 ++--- my/instagram/gdpr.py | 19 +++++----- my/instapaper.py | 10 ++++-- my/ip/all.py | 3 +- my/ip/common.py | 7 ++-- my/jawbone/__init__.py | 23 ++++++------ my/jawbone/plots.py | 17 ++++----- my/kobo.py | 31 +++++++++-------- my/kython/kompress.py | 3 +- my/lastfm.py | 14 +++++--- my/location/all.py | 5 ++- my/location/common.py | 11 +++--- my/location/fallback/all.py | 10 +++--- my/location/fallback/common.py | 31 +++++++++-------- my/location/fallback/via_home.py | 32 ++++++++--------- my/location/fallback/via_ip.py | 8 ++--- my/location/google.py | 21 ++++++----- my/location/google_takeout.py | 7 ++-- my/location/google_takeout_semantic.py | 11 +++--- my/location/gpslogger.py | 10 +++--- my/location/home.py | 4 +-- my/location/via_ip.py | 4 +-- my/materialistic.py | 1 + my/media/imdb.py | 10 +++--- my/media/youtube.py | 2 +- my/monzo/monzoexport.py | 5 +-- my/orgmode.py | 10 +++--- my/pdfs.py | 14 ++++---- my/photos/main.py | 29 +++++++++------- my/photos/utils.py | 15 ++++---- my/pinboard.py | 9 ++--- my/pocket.py | 12 ++++--- my/polar.py | 33 ++++++++++-------- my/reddit/__init__.py | 1 + my/reddit/all.py | 7 ++-- my/reddit/common.py | 10 +++--- my/reddit/pushshift.py | 12 +++---- my/reddit/rexport.py | 17 ++++----- my/rescuetime.py | 23 +++++++----- my/roamresearch.py | 29 +++++++++------- my/rss/all.py | 4 +-- my/rss/common.py | 16 +++++---- my/rss/feedbin.py | 8 ++--- my/rss/feedly.py | 3 +- my/rtm.py | 24 ++++++------- my/runnerup.py | 14 ++++---- my/simple.py | 5 ++- my/smscalls.py | 48 ++++++++++++++------------ my/stackexchange/gdpr.py | 20 ++++++++--- my/stackexchange/stexport.py | 3 +- my/taplog.py | 14 ++++---- my/telegram/telegram_backup.py | 30 ++++++++-------- my/tests/bluemaestro.py | 2 +- my/tests/body/weight.py | 6 ++-- my/tests/commits.py | 7 ++-- my/tests/location/fallback.py | 2 +- my/tests/reddit.py | 10 +++--- my/time/tz/common.py | 1 - my/time/tz/main.py | 1 + my/time/tz/via_location.py | 36 +++++++++---------- my/tinder/android.py | 18 +++++----- my/topcoder.py | 8 ++--- my/twitter/all.py | 6 ++-- my/twitter/android.py | 16 ++++----- my/twitter/archive.py | 3 +- my/twitter/common.py | 10 +++--- my/twitter/talon.py | 3 +- my/twitter/twint.py | 10 +++--- my/util/hpi_heartbeat.py | 11 +++--- my/vk/favorites.py | 13 +++---- my/vk/vk_messages_backup.py | 12 +++---- my/whatsapp/android.py | 23 ++++++------ my/youtube/takeout.py | 3 +- my/zotero.py | 22 ++++++------ my/zulip/organization.py | 2 +- ruff.toml | 16 ++++----- 125 files changed, 889 insertions(+), 739 deletions(-) diff --git a/my/arbtt.py b/my/arbtt.py index 2bcf291..5d4bf8e 100644 --- a/my/arbtt.py +++ b/my/arbtt.py @@ -2,20 +2,22 @@ [[https://github.com/nomeata/arbtt#arbtt-the-automatic-rule-based-time-tracker][Arbtt]] time tracking ''' +from __future__ import annotations + REQUIRES = ['ijson', 'cffi'] # NOTE likely also needs libyajl2 from apt or elsewhere? +from collections.abc import Iterable, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Sequence, Iterable, List, Optional def inputs() -> Sequence[Path]: try: from my.config import arbtt as user_config except ImportError: - from .core.warnings import low + from my.core.warnings import low low("Couldn't find 'arbtt' config section, falling back to the default capture.log (usually in HOME dir). Add 'arbtt' section with logfiles = '' to suppress this warning.") return [] else: @@ -55,7 +57,7 @@ class Entry: return fromisoformat(ds) @property - def active(self) -> Optional[str]: + def active(self) -> str | None: # NOTE: WIP, might change this in the future... ait = (w for w in self.json['windows'] if w['active']) a = next(ait, None) @@ -74,17 +76,18 @@ class Entry: def entries() -> Iterable[Entry]: inps = list(inputs()) - base: List[PathIsh] = ['arbtt-dump', '--format=json'] + base: list[PathIsh] = ['arbtt-dump', '--format=json'] - cmds: List[List[PathIsh]] + cmds: list[list[PathIsh]] if len(inps) == 0: cmds = [base] # rely on default else: # otherwise, 'merge' them cmds = [[*base, '--logfile', f] for f in inps] - import ijson.backends.yajl2_cffi as ijson # type: ignore - from subprocess import Popen, PIPE + from subprocess import PIPE, Popen + + import ijson.backends.yajl2_cffi as ijson # type: ignore for cmd in cmds: with Popen(cmd, stdout=PIPE) as p: out = p.stdout; assert out is not None @@ -93,8 +96,8 @@ def entries() -> Iterable[Entry]: def fill_influxdb() -> None: - from .core.influxdb import magic_fill from .core.freezer import Freezer + from .core.influxdb import magic_fill freezer = Freezer(Entry) fit = (freezer.freeze(e) for e in entries()) # TODO crap, influxdb doesn't like None https://github.com/influxdata/influxdb/issues/7722 @@ -106,6 +109,8 @@ def fill_influxdb() -> None: magic_fill(fit, name=f'{entries.__module__}:{entries.__name__}') -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: return stat(entries) diff --git a/my/bluemaestro.py b/my/bluemaestro.py index 4c33fd1..8c739f0 100644 --- a/my/bluemaestro.py +++ b/my/bluemaestro.py @@ -2,14 +2,17 @@ [[https://bluemaestro.com/products/product-details/bluetooth-environmental-monitor-and-logger][Bluemaestro]] temperature/humidity/pressure monitor """ +from __future__ import annotations + # todo most of it belongs to DAL... but considering so few people use it I didn't bother for now import re import sqlite3 from abc import abstractmethod +from collections.abc import Iterable, Sequence from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path -from typing import Iterable, Optional, Protocol, Sequence, Set +from typing import Protocol import pytz @@ -87,17 +90,17 @@ def measurements() -> Iterable[Res[Measurement]]: total = len(paths) width = len(str(total)) - last: Optional[datetime] = None + last: datetime | None = None # tables are immutable, so can save on processing.. - processed_tables: Set[str] = set() + processed_tables: set[str] = set() for idx, path in enumerate(paths): logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') tot = 0 new = 0 # todo assert increasing timestamp? with sqlite_connect_immutable(path) as db: - db_dt: Optional[datetime] = None + db_dt: datetime | None = None try: datas = db.execute( f'SELECT "{path.name}" as name, Time, Temperature, Humidity, Pressure, Dewpoint FROM data ORDER BY log_index' diff --git a/my/body/blood.py b/my/body/blood.py index fb035eb..867568c 100644 --- a/my/body/blood.py +++ b/my/body/blood.py @@ -2,41 +2,42 @@ Blood tracking (manual org-mode entries) """ +from __future__ import annotations + +from collections.abc import Iterable from datetime import datetime -from typing import Iterable, NamedTuple, Optional +from typing import NamedTuple -from ..core.error import Res -from ..core.orgmode import parse_org_datetime, one_table - - -import pandas as pd import orgparse - +import pandas as pd from my.config import blood as config # type: ignore[attr-defined] +from ..core.error import Res +from ..core.orgmode import one_table, parse_org_datetime + class Entry(NamedTuple): dt: datetime - ketones : Optional[float]=None - glucose : Optional[float]=None + ketones : float | None=None + glucose : float | None=None - vitamin_d : Optional[float]=None - vitamin_b12 : Optional[float]=None + vitamin_d : float | None=None + vitamin_b12 : float | None=None - hdl : Optional[float]=None - ldl : Optional[float]=None - triglycerides: Optional[float]=None + hdl : float | None=None + ldl : float | None=None + triglycerides: float | None=None - source : Optional[str]=None - extra : Optional[str]=None + source : str | None=None + extra : str | None=None Result = Res[Entry] -def try_float(s: str) -> Optional[float]: +def try_float(s: str) -> float | None: l = s.split() if len(l) == 0: return None @@ -105,6 +106,7 @@ def blood_tests_data() -> Iterable[Result]: def data() -> Iterable[Result]: from itertools import chain + from ..core.error import sort_res_by datas = chain(glucose_ketones_data(), blood_tests_data()) return sort_res_by(datas, key=lambda e: e.dt) diff --git a/my/body/exercise/all.py b/my/body/exercise/all.py index e86a5af..d0df747 100644 --- a/my/body/exercise/all.py +++ b/my/body/exercise/all.py @@ -7,10 +7,10 @@ from ...core.pandas import DataFrameT, check_dataframe @check_dataframe def dataframe() -> DataFrameT: # this should be somehow more flexible... - from ...endomondo import dataframe as EDF - from ...runnerup import dataframe as RDF - import pandas as pd + + from ...endomondo import dataframe as EDF + from ...runnerup import dataframe as RDF return pd.concat([ EDF(), RDF(), diff --git a/my/body/exercise/cardio.py b/my/body/exercise/cardio.py index 083b972..d8a6afd 100644 --- a/my/body/exercise/cardio.py +++ b/my/body/exercise/cardio.py @@ -3,7 +3,6 @@ Cardio data, filtered from various data sources ''' from ...core.pandas import DataFrameT, check_dataframe - CARDIO = { 'Running', 'Running, treadmill', diff --git a/my/body/exercise/cross_trainer.py b/my/body/exercise/cross_trainer.py index edbb557..30f96f9 100644 --- a/my/body/exercise/cross_trainer.py +++ b/my/body/exercise/cross_trainer.py @@ -5,16 +5,18 @@ This is probably too specific to my needs, so later I will move it away to a per For now it's worth keeping it here as an example and perhaps utility functions might be useful for other HPI modules. ''' -from datetime import datetime, timedelta -from typing import Optional +from __future__ import annotations -from ...core.pandas import DataFrameT, check_dataframe as cdf -from ...core.orgmode import collect, Table, parse_org_datetime, TypedTable +from datetime import datetime, timedelta + +import pytz from my.config import exercise as config +from ...core.orgmode import Table, TypedTable, collect, parse_org_datetime +from ...core.pandas import DataFrameT +from ...core.pandas import check_dataframe as cdf -import pytz # FIXME how to attach it properly? tz = pytz.timezone('Europe/London') @@ -114,7 +116,7 @@ def dataframe() -> DataFrameT: rows.append(rd) # presumably has an error set continue - idx: Optional[int] + idx: int | None close = edf[edf['start_time'].apply(lambda t: pd_date_diff(t, mdate)).abs() < _DELTA] if len(close) == 0: idx = None @@ -163,7 +165,9 @@ def dataframe() -> DataFrameT: # TODO wtf?? where is speed coming from?? -from ...core import stat, Stats +from ...core import Stats, stat + + def stats() -> Stats: return stat(cross_trainer_data) diff --git a/my/body/sleep/common.py b/my/body/sleep/common.py index 1100814..fc288e5 100644 --- a/my/body/sleep/common.py +++ b/my/body/sleep/common.py @@ -1,5 +1,6 @@ -from ...core import stat, Stats -from ...core.pandas import DataFrameT, check_dataframe as cdf +from ...core import Stats, stat +from ...core.pandas import DataFrameT +from ...core.pandas import check_dataframe as cdf class Combine: diff --git a/my/body/sleep/main.py b/my/body/sleep/main.py index 29b12a7..2460e03 100644 --- a/my/body/sleep/main.py +++ b/my/body/sleep/main.py @@ -1,7 +1,6 @@ -from ... import jawbone -from ... import emfit - +from ... import emfit, jawbone from .common import Combine + _combined = Combine([ jawbone, emfit, diff --git a/my/body/weight.py b/my/body/weight.py index 51e6513..d5478ef 100644 --- a/my/body/weight.py +++ b/my/body/weight.py @@ -2,14 +2,14 @@ Weight data (manually logged) ''' +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime -from typing import Any, Iterator - -from my.core import make_logger -from my.core.error import Res, extract_error_datetime, set_error_datetime +from typing import Any from my import orgmode +from my.core import make_logger +from my.core.error import Res, extract_error_datetime, set_error_datetime config = Any diff --git a/my/books/kobo.py b/my/books/kobo.py index 2a469d0..899ef31 100644 --- a/my/books/kobo.py +++ b/my/books/kobo.py @@ -1,7 +1,6 @@ -from ..core import warnings +from my.core import warnings warnings.high('my.books.kobo is deprecated! Please use my.kobo instead!') -from ..core.util import __NOT_HPI_MODULE__ - -from ..kobo import * # type: ignore[no-redef] +from my.core.util import __NOT_HPI_MODULE__ +from my.kobo import * # type: ignore[no-redef] diff --git a/my/browser/active_browser.py b/my/browser/active_browser.py index 6f335bd..8051f1b 100644 --- a/my/browser/active_browser.py +++ b/my/browser/active_browser.py @@ -19,16 +19,18 @@ class config(user_config.active_browser): export_path: Paths +from collections.abc import Iterator, Sequence from pathlib import Path -from typing import Sequence, Iterator -from my.core import get_files, Stats, make_logger -from browserexport.merge import read_visits, Visit +from browserexport.merge import Visit, read_visits from sqlite_backup import sqlite_backup +from my.core import Stats, get_files, make_logger + logger = make_logger(__name__) from .common import _patch_browserexport_logs + _patch_browserexport_logs(logger.level) diff --git a/my/browser/all.py b/my/browser/all.py index a7d12b4..feb973a 100644 --- a/my/browser/all.py +++ b/my/browser/all.py @@ -1,9 +1,9 @@ -from typing import Iterator +from collections.abc import Iterator + +from browserexport.merge import Visit, merge_visits from my.core import Stats from my.core.source import import_source -from browserexport.merge import merge_visits, Visit - src_export = import_source(module_name="my.browser.export") src_active = import_source(module_name="my.browser.active_browser") diff --git a/my/browser/export.py b/my/browser/export.py index 1b428b5..351cf6e 100644 --- a/my/browser/export.py +++ b/my/browser/export.py @@ -4,11 +4,12 @@ Parses browser history using [[http://github.com/seanbreckenridge/browserexport] REQUIRES = ["browserexport"] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Iterator, Sequence -import my.config +from browserexport.merge import Visit, read_and_merge + from my.core import ( Paths, Stats, @@ -18,10 +19,10 @@ from my.core import ( ) from my.core.cachew import mcachew -from browserexport.merge import read_and_merge, Visit - from .common import _patch_browserexport_logs +import my.config # isort: skip + @dataclass class config(my.config.browser.export): diff --git a/my/bumble/android.py b/my/bumble/android.py index 54a0441..3f9fa13 100644 --- a/my/bumble/android.py +++ b/my/bumble/android.py @@ -3,24 +3,24 @@ Bumble data from Android app database (in =/data/data/com.bumble.app/databases/C """ from __future__ import annotations +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime -from typing import Iterator, Sequence, Optional, Dict +from pathlib import Path from more_itertools import unique_everseen -from my.config import bumble as user_config +from my.core import Paths, get_files + +from my.config import bumble as user_config # isort: skip -from ..core import Paths @dataclass class config(user_config.android): # paths[s]/glob to the exported sqlite databases export_path: Paths -from ..core import get_files -from pathlib import Path def inputs() -> Sequence[Path]: return get_files(config.export_path) @@ -43,22 +43,24 @@ class _BaseMessage: @dataclass(unsafe_hash=True) class _Message(_BaseMessage): conversation_id: str - reply_to_id: Optional[str] + reply_to_id: str | None @dataclass(unsafe_hash=True) class Message(_BaseMessage): person: Person - reply_to: Optional[Message] + reply_to: Message | None import json -from typing import Union -from ..core import Res import sqlite3 -from ..core.sqlite import sqlite_connect_immutable, select +from typing import Union + from my.core.compat import assert_never +from ..core import Res +from ..core.sqlite import select, sqlite_connect_immutable + EntitiesRes = Res[Union[Person, _Message]] def _entities() -> Iterator[EntitiesRes]: @@ -120,8 +122,8 @@ _UNKNOWN_PERSON = "UNKNOWN_PERSON" def messages() -> Iterator[Res[Message]]: - id2person: Dict[str, Person] = {} - id2msg: Dict[str, Message] = {} + id2person: dict[str, Person] = {} + id2msg: dict[str, Message] = {} for x in unique_everseen(_entities(), key=_key): if isinstance(x, Exception): yield x diff --git a/my/calendar/holidays.py b/my/calendar/holidays.py index af51696..522672e 100644 --- a/my/calendar/holidays.py +++ b/my/calendar/holidays.py @@ -15,7 +15,8 @@ from my.core.time import zone_to_countrycode @lru_cache(1) def _calendar(): - from workalendar.registry import registry # type: ignore + from workalendar.registry import registry # type: ignore + # todo switch to using time.tz.main once _get_tz stabilizes? from ..time.tz import via_location as LTZ # TODO would be nice to do it dynamically depending on the past timezones... diff --git a/my/cfg.py b/my/cfg.py index e4020b4..9331e8a 100644 --- a/my/cfg.py +++ b/my/cfg.py @@ -1,7 +1,6 @@ import my.config as config from .core import __NOT_HPI_MODULE__ - from .core import warnings as W # still used in Promnesia, maybe in dashboard? diff --git a/my/codeforces.py b/my/codeforces.py index f2d150a..9c6b7c9 100644 --- a/my/codeforces.py +++ b/my/codeforces.py @@ -1,13 +1,12 @@ +import json +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from functools import cached_property -import json from pathlib import Path -from typing import Dict, Iterator, Sequence - -from my.core import get_files, Res, datetime_aware from my.config import codeforces as config # type: ignore[attr-defined] +from my.core import Res, datetime_aware, get_files def inputs() -> Sequence[Path]: @@ -39,7 +38,7 @@ class Competition: class Parser: def __init__(self, *, inputs: Sequence[Path]) -> None: self.inputs = inputs - self.contests: Dict[ContestId, Contest] = {} + self.contests: dict[ContestId, Contest] = {} def _parse_allcontests(self, p: Path) -> Iterator[Contest]: j = json.loads(p.read_text()) diff --git a/my/coding/commits.py b/my/coding/commits.py index 31c366e..fe17dee 100644 --- a/my/coding/commits.py +++ b/my/coding/commits.py @@ -1,29 +1,32 @@ """ Git commits data for repositories on your filesystem """ + +from __future__ import annotations + REQUIRES = [ 'gitpython', ] - import shutil -from pathlib import Path -from datetime import datetime, timezone +from collections.abc import Iterator, Sequence from dataclasses import dataclass, field -from typing import List, Optional, Iterator, Set, Sequence, cast +from datetime import datetime, timezone +from pathlib import Path +from typing import Optional, cast - -from my.core import PathIsh, LazyLogger, make_config +from my.core import LazyLogger, PathIsh, make_config from my.core.cachew import cache_dir, mcachew from my.core.warnings import high +from my.config import commits as user_config # isort: skip + -from my.config import commits as user_config @dataclass class commits_cfg(user_config): roots: Sequence[PathIsh] = field(default_factory=list) - emails: Optional[Sequence[str]] = None - names: Optional[Sequence[str]] = None + emails: Sequence[str] | None = None + names: Sequence[str] | None = None # experiment to make it lazy? @@ -40,7 +43,6 @@ def config() -> commits_cfg: import git from git.repo.fun import is_git_dir - log = LazyLogger(__name__, level='info') @@ -93,7 +95,7 @@ def _git_root(git_dir: PathIsh) -> Path: return gd # must be bare -def _repo_commits_aux(gr: git.Repo, rev: str, emitted: Set[str]) -> Iterator[Commit]: +def _repo_commits_aux(gr: git.Repo, rev: str, emitted: set[str]) -> Iterator[Commit]: # without path might not handle pull heads properly for c in gr.iter_commits(rev=rev): if not by_me(c): @@ -120,7 +122,7 @@ def _repo_commits_aux(gr: git.Repo, rev: str, emitted: Set[str]) -> Iterator[Com def repo_commits(repo: PathIsh): gr = git.Repo(str(repo)) - emitted: Set[str] = set() + emitted: set[str] = set() for r in gr.references: yield from _repo_commits_aux(gr=gr, rev=r.path, emitted=emitted) @@ -141,14 +143,14 @@ def canonical_name(repo: Path) -> str: def _fd_path() -> str: # todo move it to core - fd_path: Optional[str] = shutil.which("fdfind") or shutil.which("fd-find") or shutil.which("fd") + fd_path: str | None = shutil.which("fdfind") or shutil.which("fd-find") or shutil.which("fd") if fd_path is None: high("my.coding.commits requires 'fd' to be installed, See https://github.com/sharkdp/fd#installation") assert fd_path is not None return fd_path -def git_repos_in(roots: List[Path]) -> List[Path]: +def git_repos_in(roots: list[Path]) -> list[Path]: from subprocess import check_output outputs = check_output([ _fd_path(), @@ -172,7 +174,7 @@ def git_repos_in(roots: List[Path]) -> List[Path]: return repos -def repos() -> List[Path]: +def repos() -> list[Path]: return git_repos_in(list(map(Path, config().roots))) @@ -190,7 +192,7 @@ def _repo_depends_on(_repo: Path) -> int: raise RuntimeError(f"Could not find a FETCH_HEAD/HEAD file in {_repo}") -def _commits(_repos: List[Path]) -> Iterator[Commit]: +def _commits(_repos: list[Path]) -> Iterator[Commit]: for r in _repos: yield from _cached_commits(r) diff --git a/my/common.py b/my/common.py index 1b56fb5..22e9487 100644 --- a/my/common.py +++ b/my/common.py @@ -1,6 +1,6 @@ from .core.warnings import high + high("DEPRECATED! Please use my.core.common instead.") from .core import __NOT_HPI_MODULE__ - from .core.common import * diff --git a/my/config.py b/my/config.py index 2dd9cda..301bf49 100644 --- a/my/config.py +++ b/my/config.py @@ -9,17 +9,18 @@ This file is used for: - mypy: this file provides some type annotations - for loading the actual user config ''' + +from __future__ import annotations + #### NOTE: you won't need this line VVVV in your personal config -from my.core import init # noqa: F401 +from my.core import init # noqa: F401 # isort: skip ### from datetime import tzinfo from pathlib import Path -from typing import List - -from my.core import Paths, PathIsh +from my.core import PathIsh, Paths class hypothesis: @@ -75,14 +76,16 @@ class google: takeout_path: Paths = '' -from typing import Sequence, Union, Tuple -from datetime import datetime, date, timedelta +from collections.abc import Sequence +from datetime import date, datetime, timedelta +from typing import Union + DateIsh = Union[datetime, date, str] -LatLon = Tuple[float, float] +LatLon = tuple[float, float] class location: # todo ugh, need to think about it... mypy wants the type here to be general, otherwise it can't deduce # and we can't import the types from the module itself, otherwise would be circular. common module? - home: Union[LatLon, Sequence[Tuple[DateIsh, LatLon]]] = (1.0, -1.0) + home: LatLon | Sequence[tuple[DateIsh, LatLon]] = (1.0, -1.0) home_accuracy = 30_000.0 class via_ip: @@ -103,6 +106,8 @@ class location: from typing import Literal + + class time: class tz: policy: Literal['keep', 'convert', 'throw'] @@ -121,10 +126,9 @@ class arbtt: logfiles: Paths -from typing import Optional class commits: - emails: Optional[Sequence[str]] - names: Optional[Sequence[str]] + emails: Sequence[str] | None + names: Sequence[str] | None roots: Sequence[PathIsh] @@ -150,8 +154,8 @@ class tinder: class instagram: class android: export_path: Paths - username: Optional[str] - full_name: Optional[str] + username: str | None + full_name: str | None class gdpr: export_path: Paths @@ -169,7 +173,7 @@ class materialistic: class fbmessenger: class fbmessengerexport: export_db: PathIsh - facebook_id: Optional[str] + facebook_id: str | None class android: export_path: Paths @@ -247,7 +251,7 @@ class runnerup: class emfit: export_path: Path timezone: tzinfo - excluded_sids: List[str] + excluded_sids: list[str] class foursquare: @@ -270,7 +274,7 @@ class roamresearch: class whatsapp: class android: export_path: Paths - my_user_id: Optional[str] + my_user_id: str | None class harmonic: diff --git a/my/core/_deprecated/kompress.py b/my/core/_deprecated/kompress.py index ce14fad..c3f333f 100644 --- a/my/core/_deprecated/kompress.py +++ b/my/core/_deprecated/kompress.py @@ -11,7 +11,7 @@ from collections.abc import Iterator, Sequence from datetime import datetime from functools import total_ordering from pathlib import Path -from typing import IO, Any, Union +from typing import IO, Union PathIsh = Union[Path, str] diff --git a/my/core/common.py b/my/core/common.py index 91fe9bd..aa994ea 100644 --- a/my/core/common.py +++ b/my/core/common.py @@ -63,7 +63,7 @@ def get_files( if '*' in gs: if glob != DEFAULT_GLOB: warnings.medium(f"{caller()}: treating {gs} as glob path. Explicit glob={glob} argument is ignored!") - paths.extend(map(Path, do_glob(gs))) + paths.extend(map(Path, do_glob(gs))) # noqa: PTH207 elif os.path.isdir(str(src)): # noqa: PTH112 # NOTE: we're using os.path here on purpose instead of src.is_dir # the reason is is_dir for archives might return True and then @@ -157,7 +157,7 @@ def get_valid_filename(s: str) -> str: # TODO deprecate and suggest to use one from my.core directly? not sure -from .utils.itertools import unique_everseen +from .utils.itertools import unique_everseen # noqa: F401 ### legacy imports, keeping them here for backwards compatibility ## hiding behind TYPE_CHECKING so it works in runtime diff --git a/my/demo.py b/my/demo.py index 0c54792..fa80b2a 100644 --- a/my/demo.py +++ b/my/demo.py @@ -1,12 +1,14 @@ ''' Just a demo module for testing and documentation purposes ''' +from __future__ import annotations import json +from collections.abc import Iterable, Sequence from dataclasses import dataclass from datetime import datetime, timezone, tzinfo from pathlib import Path -from typing import Iterable, Optional, Protocol, Sequence +from typing import Protocol from my.core import Json, PathIsh, Paths, get_files @@ -20,7 +22,7 @@ class config(Protocol): # this is to check optional attribute handling timezone: tzinfo = timezone.utc - external: Optional[PathIsh] = None + external: PathIsh | None = None @property def external_module(self): diff --git a/my/emfit/__init__.py b/my/emfit/__init__.py index 9934903..0d50b06 100644 --- a/my/emfit/__init__.py +++ b/my/emfit/__init__.py @@ -4,31 +4,34 @@ Consumes data exported by https://github.com/karlicoss/emfitexport """ +from __future__ import annotations + REQUIRES = [ 'git+https://github.com/karlicoss/emfitexport', ] -from contextlib import contextmanager import dataclasses -from datetime import datetime, time, timedelta import inspect +from collections.abc import Iterable, Iterator +from contextlib import contextmanager +from datetime import datetime, time, timedelta from pathlib import Path -from typing import Any, Dict, Iterable, Iterator, List, Optional - -from my.core import ( - get_files, - stat, - Res, - Stats, -) -from my.core.cachew import cache_dir, mcachew -from my.core.error import set_error_datetime, extract_error_datetime -from my.core.pandas import DataFrameT - -from my.config import emfit as config +from typing import Any import emfitexport.dal as dal +from my.core import ( + Res, + Stats, + get_files, + stat, +) +from my.core.cachew import cache_dir, mcachew +from my.core.error import extract_error_datetime, set_error_datetime +from my.core.pandas import DataFrameT + +from my.config import emfit as config # isort: skip + Emfit = dal.Emfit @@ -85,7 +88,7 @@ def datas() -> Iterable[Res[Emfit]]: # TODO should be used for jawbone data as well? def pre_dataframe() -> Iterable[Res[Emfit]]: # TODO shit. I need some sort of interrupted sleep detection? - g: List[Emfit] = [] + g: list[Emfit] = [] def flush() -> Iterable[Res[Emfit]]: if len(g) == 0: @@ -112,10 +115,10 @@ def pre_dataframe() -> Iterable[Res[Emfit]]: def dataframe() -> DataFrameT: - dicts: List[Dict[str, Any]] = [] - last: Optional[Emfit] = None + dicts: list[dict[str, Any]] = [] + last: Emfit | None = None for s in pre_dataframe(): - d: Dict[str, Any] + d: dict[str, Any] if isinstance(s, Exception): edt = extract_error_datetime(s) d = { @@ -166,11 +169,12 @@ def stats() -> Stats: @contextmanager def fake_data(nights: int = 500) -> Iterator: - from my.core.cfg import tmp_config from tempfile import TemporaryDirectory import pytz + from my.core.cfg import tmp_config + with TemporaryDirectory() as td: tdir = Path(td) gen = dal.FakeData() @@ -187,7 +191,7 @@ def fake_data(nights: int = 500) -> Iterator: # TODO remove/deprecate it? I think used by timeline -def get_datas() -> List[Emfit]: +def get_datas() -> list[Emfit]: # todo ugh. run lint properly return sorted(datas(), key=lambda e: e.start) # type: ignore diff --git a/my/endomondo.py b/my/endomondo.py index 293a542..7732c00 100644 --- a/my/endomondo.py +++ b/my/endomondo.py @@ -7,13 +7,14 @@ REQUIRES = [ ] # todo use ast in setup.py or doctor to extract the corresponding pip packages? +from collections.abc import Iterable, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Sequence, Iterable + +from my.config import endomondo as user_config from .core import Paths, get_files -from my.config import endomondo as user_config @dataclass class endomondo(user_config): @@ -33,15 +34,17 @@ def inputs() -> Sequence[Path]: import endoexport.dal as dal from endoexport.dal import Point, Workout # noqa: F401 - from .core import Res + + # todo cachew? def workouts() -> Iterable[Res[Workout]]: _dal = dal.DAL(inputs()) yield from _dal.workouts() -from .core.pandas import check_dataframe, DataFrameT +from .core.pandas import DataFrameT, check_dataframe + @check_dataframe def dataframe(*, defensive: bool=True) -> DataFrameT: @@ -75,7 +78,9 @@ def dataframe(*, defensive: bool=True) -> DataFrameT: return df -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: return { # todo pretty print stats? @@ -86,13 +91,16 @@ def stats() -> Stats: # TODO make sure it's possible to 'advise' functions and override stuff +from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterator + + @contextmanager def fake_data(count: int=100) -> Iterator: - from my.core.cfg import tmp_config - from tempfile import TemporaryDirectory import json + from tempfile import TemporaryDirectory + + from my.core.cfg import tmp_config with TemporaryDirectory() as td: tdir = Path(td) fd = dal.FakeData() diff --git a/my/error.py b/my/error.py index c0b734c..e3c1e11 100644 --- a/my/error.py +++ b/my/error.py @@ -1,6 +1,6 @@ from .core.warnings import high + high("DEPRECATED! Please use my.core.error instead.") from .core import __NOT_HPI_MODULE__ - from .core.error import * diff --git a/my/experimental/destructive_parsing.py b/my/experimental/destructive_parsing.py index b389f7e..0c4092a 100644 --- a/my/experimental/destructive_parsing.py +++ b/my/experimental/destructive_parsing.py @@ -1,5 +1,6 @@ +from collections.abc import Iterator from dataclasses import dataclass -from typing import Any, Iterator, List, Tuple +from typing import Any from my.core.compat import NoneType, assert_never @@ -9,7 +10,7 @@ from my.core.compat import NoneType, assert_never class Helper: manager: 'Manager' item: Any # todo realistically, list or dict? could at least type as indexable or something - path: Tuple[str, ...] + path: tuple[str, ...] def pop_if_primitive(self, *keys: str) -> None: """ @@ -40,9 +41,9 @@ def is_empty(x) -> bool: class Manager: def __init__(self) -> None: - self.helpers: List[Helper] = [] + self.helpers: list[Helper] = [] - def helper(self, item: Any, *, path: Tuple[str, ...] = ()) -> Helper: + def helper(self, item: Any, *, path: tuple[str, ...] = ()) -> Helper: res = Helper(manager=self, item=item, path=path) self.helpers.append(res) return res diff --git a/my/fbmessenger/__init__.py b/my/fbmessenger/__init__.py index 40fb235..f729de9 100644 --- a/my/fbmessenger/__init__.py +++ b/my/fbmessenger/__init__.py @@ -20,6 +20,7 @@ REQUIRES = [ from my.core.hpi_compat import handle_legacy_import + is_legacy_import = handle_legacy_import( parent_module_name=__name__, legacy_submodule_name='export', diff --git a/my/fbmessenger/all.py b/my/fbmessenger/all.py index 13689db..a057dca 100644 --- a/my/fbmessenger/all.py +++ b/my/fbmessenger/all.py @@ -1,10 +1,10 @@ -from typing import Iterator -from my.core import Res, stat, Stats +from collections.abc import Iterator + +from my.core import Res, Stats from my.core.source import import_source from .common import Message, _merge_messages - src_export = import_source(module_name='my.fbmessenger.export') src_android = import_source(module_name='my.fbmessenger.android') diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index effabab..a16d924 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -4,19 +4,20 @@ Messenger data from Android app database (in =/data/data/com.facebook.orca/datab from __future__ import annotations +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -import sqlite3 -from typing import Iterator, Sequence, Optional, Dict, Union, List +from typing import Union -from my.core import get_files, Paths, datetime_aware, Res, LazyLogger, make_config +from my.core import LazyLogger, Paths, Res, datetime_aware, get_files, make_config from my.core.common import unique_everseen from my.core.compat import assert_never from my.core.error import echain from my.core.sqlite import sqlite_connection -from my.config import fbmessenger as user_config +from my.config import fbmessenger as user_config # isort: skip logger = LazyLogger(__name__) @@ -27,7 +28,7 @@ class Config(user_config.android): # paths[s]/glob to the exported sqlite databases export_path: Paths - facebook_id: Optional[str] = None + facebook_id: str | None = None # hmm. this is necessary for default value (= None) to work @@ -42,13 +43,13 @@ def inputs() -> Sequence[Path]: @dataclass(unsafe_hash=True) class Sender: id: str - name: Optional[str] + name: str | None @dataclass(unsafe_hash=True) class Thread: id: str - name: Optional[str] # isn't set for groups or one to one messages + name: str | None # isn't set for groups or one to one messages # todo not sure about order of fields... @@ -56,14 +57,14 @@ class Thread: class _BaseMessage: id: str dt: datetime_aware - text: Optional[str] + text: str | None @dataclass(unsafe_hash=True) class _Message(_BaseMessage): thread_id: str sender_id: str - reply_to_id: Optional[str] + reply_to_id: str | None # todo hmm, on the one hand would be kinda nice to inherit common.Message protocol here @@ -72,7 +73,7 @@ class _Message(_BaseMessage): class Message(_BaseMessage): thread: Thread sender: Sender - reply_to: Optional[Message] + reply_to: Message | None Entity = Union[Sender, Thread, _Message] @@ -110,7 +111,7 @@ def _normalise_thread_id(key) -> str: # NOTE: this is sort of copy pasted from other _process_db method # maybe later could unify them def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: - senders: Dict[str, Sender] = {} + senders: dict[str, Sender] = {} for r in db.execute('SELECT CAST(id AS TEXT) AS id, name FROM contacts'): s = Sender( id=r['id'], # looks like it's server id? same used on facebook site @@ -127,7 +128,7 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: # TODO can we get it from db? could infer as the most common id perhaps? self_id = config.facebook_id - thread_users: Dict[str, List[Sender]] = {} + thread_users: dict[str, list[Sender]] = {} for r in db.execute('SELECT CAST(thread_key AS TEXT) AS thread_key, CAST(contact_id AS TEXT) AS contact_id FROM participants'): thread_key = r['thread_key'] user_key = r['contact_id'] @@ -193,7 +194,7 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]: - senders: Dict[str, Sender] = {} + senders: dict[str, Sender] = {} for r in db.execute('''SELECT * FROM thread_users'''): # for messaging_actor_type == 'REDUCED_MESSAGING_ACTOR', name is None # but they are still referenced, so need to keep @@ -207,7 +208,7 @@ def _process_db_threads_db2(db: sqlite3.Connection) -> Iterator[Res[Entity]]: yield s self_id = config.facebook_id - thread_users: Dict[str, List[Sender]] = {} + thread_users: dict[str, list[Sender]] = {} for r in db.execute('SELECT * from thread_participants'): thread_key = r['thread_key'] user_key = r['user_key'] @@ -267,9 +268,9 @@ def contacts() -> Iterator[Res[Sender]]: def messages() -> Iterator[Res[Message]]: - senders: Dict[str, Sender] = {} - msgs: Dict[str, Message] = {} - threads: Dict[str, Thread] = {} + senders: dict[str, Sender] = {} + msgs: dict[str, Message] = {} + threads: dict[str, Thread] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x diff --git a/my/fbmessenger/common.py b/my/fbmessenger/common.py index 33d1b20..0f5a374 100644 --- a/my/fbmessenger/common.py +++ b/my/fbmessenger/common.py @@ -1,6 +1,9 @@ -from my.core import __NOT_HPI_MODULE__ +from __future__ import annotations -from typing import Iterator, Optional, Protocol +from my.core import __NOT_HPI_MODULE__ # isort: skip + +from collections.abc import Iterator +from typing import Protocol from my.core import datetime_aware @@ -10,7 +13,7 @@ class Thread(Protocol): def id(self) -> str: ... @property - def name(self) -> Optional[str]: ... + def name(self) -> str | None: ... class Sender(Protocol): @@ -18,7 +21,7 @@ class Sender(Protocol): def id(self) -> str: ... @property - def name(self) -> Optional[str]: ... + def name(self) -> str | None: ... class Message(Protocol): @@ -29,7 +32,7 @@ class Message(Protocol): def dt(self) -> datetime_aware: ... @property - def text(self) -> Optional[str]: ... + def text(self) -> str | None: ... @property def thread(self) -> Thread: ... @@ -39,8 +42,11 @@ class Message(Protocol): from itertools import chain + from more_itertools import unique_everseen -from my.core import warn_if_empty, Res + +from my.core import Res, warn_if_empty + @warn_if_empty def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]: diff --git a/my/fbmessenger/export.py b/my/fbmessenger/export.py index 201fad8..3b06618 100644 --- a/my/fbmessenger/export.py +++ b/my/fbmessenger/export.py @@ -7,16 +7,15 @@ REQUIRES = [ 'git+https://github.com/karlicoss/fbmessengerexport', ] +from collections.abc import Iterator from contextlib import ExitStack, contextmanager from dataclasses import dataclass -from typing import Iterator - -from my.core import PathIsh, Res, stat, Stats -from my.core.warnings import high -from my.config import fbmessenger as user_config import fbmessengerexport.dal as messenger +from my.config import fbmessenger as user_config +from my.core import PathIsh, Res, Stats, stat +from my.core.warnings import high ### # support old style config diff --git a/my/foursquare.py b/my/foursquare.py index 394fdf3..3b418aa 100644 --- a/my/foursquare.py +++ b/my/foursquare.py @@ -2,15 +2,14 @@ Foursquare/Swarm checkins ''' -from datetime import datetime, timezone, timedelta -from itertools import chain import json +from datetime import datetime, timedelta, timezone +from itertools import chain -# TODO pytz for timezone??? - -from my.core import get_files, make_logger from my.config import foursquare as config +# TODO pytz for timezone??? +from my.core import get_files, make_logger logger = make_logger(__name__) diff --git a/my/github/all.py b/my/github/all.py index f885dde..f5e13cf 100644 --- a/my/github/all.py +++ b/my/github/all.py @@ -3,8 +3,7 @@ Unified Github data (merged from GDPR export and periodic API updates) """ from . import gdpr, ghexport - -from .common import merge_events, Results +from .common import Results, merge_events def events() -> Results: diff --git a/my/github/common.py b/my/github/common.py index e54bc4d..22ba47e 100644 --- a/my/github/common.py +++ b/my/github/common.py @@ -1,24 +1,27 @@ """ Github events and their metadata: comments/issues/pull requests """ -from ..core import __NOT_HPI_MODULE__ + +from __future__ import annotations + +from my.core import __NOT_HPI_MODULE__ # isort: skip +from collections.abc import Iterable from datetime import datetime, timezone -from typing import Optional, NamedTuple, Iterable, Set, Tuple +from typing import NamedTuple, Optional -from ..core import warn_if_empty, LazyLogger -from ..core.error import Res +from my.core import make_logger, warn_if_empty +from my.core.error import Res - -logger = LazyLogger(__name__) +logger = make_logger(__name__) class Event(NamedTuple): dt: datetime summary: str eid: str link: Optional[str] - body: Optional[str]=None + body: Optional[str] = None is_bot: bool = False @@ -27,7 +30,7 @@ Results = Iterable[Res[Event]] @warn_if_empty def merge_events(*sources: Results) -> Results: from itertools import chain - emitted: Set[Tuple[datetime, str]] = set() + emitted: set[tuple[datetime, str]] = set() for e in chain(*sources): if isinstance(e, Exception): yield e @@ -52,7 +55,7 @@ def parse_dt(s: str) -> datetime: # experimental way of supportint event ids... not sure class EventIds: @staticmethod - def repo_created(*, dts: str, name: str, ref_type: str, ref: Optional[str]) -> str: + def repo_created(*, dts: str, name: str, ref_type: str, ref: str | None) -> str: return f'{dts}_repocreated_{name}_{ref_type}_{ref}' @staticmethod diff --git a/my/github/gdpr.py b/my/github/gdpr.py index a56ff46..be56454 100644 --- a/my/github/gdpr.py +++ b/my/github/gdpr.py @@ -6,8 +6,9 @@ from __future__ import annotations import json from abc import abstractmethod +from collections.abc import Iterator, Sequence from pathlib import Path -from typing import Any, Iterator, Sequence +from typing import Any from my.core import Paths, Res, Stats, get_files, make_logger, stat, warnings from my.core.error import echain diff --git a/my/github/ghexport.py b/my/github/ghexport.py index 80106a5..3e17c10 100644 --- a/my/github/ghexport.py +++ b/my/github/ghexport.py @@ -1,13 +1,17 @@ """ Github data: events, comments, etc. (API data) """ + +from __future__ import annotations + REQUIRES = [ 'git+https://github.com/karlicoss/ghexport', ] + from dataclasses import dataclass -from my.core import Paths from my.config import github as user_config +from my.core import Paths @dataclass @@ -21,7 +25,9 @@ class github(user_config): ### -from my.core.cfg import make_config, Attrs +from my.core.cfg import Attrs, make_config + + def migration(attrs: Attrs) -> Attrs: export_dir = 'export_dir' if export_dir in attrs: # legacy name @@ -41,15 +47,14 @@ except ModuleNotFoundError as e: ############################ +from collections.abc import Sequence from functools import lru_cache from pathlib import Path -from typing import Tuple, Dict, Sequence, Optional -from my.core import get_files, LazyLogger +from my.core import LazyLogger, get_files from my.core.cachew import mcachew -from .common import Event, parse_dt, Results, EventIds - +from .common import Event, EventIds, Results, parse_dt logger = LazyLogger(__name__) @@ -82,7 +87,9 @@ def _events() -> Results: yield e -from my.core import stat, Stats +from my.core import Stats, stat + + def stats() -> Stats: return { **stat(events), @@ -99,7 +106,7 @@ def _log_if_unhandled(e) -> None: Link = str EventId = str Body = str -def _get_summary(e) -> Tuple[str, Optional[Link], Optional[EventId], Optional[Body]]: +def _get_summary(e) -> tuple[str, Link | None, EventId | None, Body | None]: # TODO would be nice to give access to raw event within timeline dts = e['created_at'] eid = e['id'] @@ -195,7 +202,7 @@ def _get_summary(e) -> Tuple[str, Optional[Link], Optional[EventId], Optional[Bo return tp, None, None, None -def _parse_event(d: Dict) -> Event: +def _parse_event(d: dict) -> Event: summary, link, eid, body = _get_summary(d) if eid is None: eid = d['id'] # meh diff --git a/my/goodreads.py b/my/goodreads.py index 864bd64..559efda 100644 --- a/my/goodreads.py +++ b/my/goodreads.py @@ -7,15 +7,18 @@ REQUIRES = [ from dataclasses import dataclass -from my.core import datetime_aware, Paths + from my.config import goodreads as user_config +from my.core import Paths, datetime_aware + @dataclass class goodreads(user_config): # paths[s]/glob to the exported JSON data export_path: Paths -from my.core.cfg import make_config, Attrs +from my.core.cfg import Attrs, make_config + def _migration(attrs: Attrs) -> Attrs: export_dir = 'export_dir' @@ -29,18 +32,19 @@ config = make_config(goodreads, migration=_migration) #############################3 -from my.core import get_files -from typing import Sequence, Iterator +from collections.abc import Iterator, Sequence from pathlib import Path +from my.core import get_files + + def inputs() -> Sequence[Path]: return get_files(config.export_path) from datetime import datetime + import pytz - - from goodrexport import dal diff --git a/my/google/maps/_android_protobuf.py b/my/google/maps/_android_protobuf.py index 1d43ae0..615623d 100644 --- a/my/google/maps/_android_protobuf.py +++ b/my/google/maps/_android_protobuf.py @@ -1,8 +1,8 @@ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip # NOTE: this tool was quite useful https://github.com/aj3423/aproto -from google.protobuf import descriptor_pool, descriptor_pb2, message_factory +from google.protobuf import descriptor_pb2, descriptor_pool, message_factory TYPE_STRING = descriptor_pb2.FieldDescriptorProto.TYPE_STRING TYPE_BYTES = descriptor_pb2.FieldDescriptorProto.TYPE_BYTES diff --git a/my/google/maps/android.py b/my/google/maps/android.py index 279231a..95ecacf 100644 --- a/my/google/maps/android.py +++ b/my/google/maps/android.py @@ -7,20 +7,20 @@ REQUIRES = [ "protobuf", # for parsing blobs from the database ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Any, Iterator, Optional, Sequence +from typing import Any from urllib.parse import quote -from my.core import datetime_aware, get_files, LazyLogger, Paths, Res +from my.core import LazyLogger, Paths, Res, datetime_aware, get_files from my.core.common import unique_everseen from my.core.sqlite import sqlite_connection -import my.config - from ._android_protobuf import parse_labeled, parse_list, parse_place +import my.config # isort: skip logger = LazyLogger(__name__) @@ -59,8 +59,8 @@ class Place: updated_at: datetime_aware # TODO double check it's utc? title: str location: Location - address: Optional[str] - note: Optional[str] + address: str | None + note: str | None @property def place_url(self) -> str: diff --git a/my/google/takeout/html.py b/my/google/takeout/html.py index 750beac..3f2b5db 100644 --- a/my/google/takeout/html.py +++ b/my/google/takeout/html.py @@ -2,18 +2,22 @@ Google Takeout exports: browsing history, search/youtube/google play activity ''' -from enum import Enum +from __future__ import annotations + +from my.core import __NOT_HPI_MODULE__ # isort: skip + import re -from pathlib import Path +from collections.abc import Iterable from datetime import datetime +from enum import Enum from html.parser import HTMLParser -from typing import List, Optional, Any, Callable, Iterable, Tuple +from pathlib import Path +from typing import Any, Callable from urllib.parse import unquote import pytz -from ...core.time import abbr_to_timezone - +from my.core.time import abbr_to_timezone # NOTE: https://bugs.python.org/issue22377 %Z doesn't work properly _TIME_FORMATS = [ @@ -36,7 +40,7 @@ def parse_dt(s: str) -> datetime: s, tzabbr = s.rsplit(maxsplit=1) tz = abbr_to_timezone(tzabbr) - dt: Optional[datetime] = None + dt: datetime | None = None for fmt in _TIME_FORMATS: try: dt = datetime.strptime(s, fmt) @@ -73,7 +77,7 @@ class State(Enum): Url = str Title = str -Parsed = Tuple[datetime, Url, Title] +Parsed = tuple[datetime, Url, Title] Callback = Callable[[datetime, Url, Title], None] @@ -83,9 +87,9 @@ class TakeoutHTMLParser(HTMLParser): super().__init__() self.state: State = State.OUTSIDE - self.title_parts: List[str] = [] - self.title: Optional[str] = None - self.url: Optional[str] = None + self.title_parts: list[str] = [] + self.title: str | None = None + self.url: str | None = None self.callback = callback @@ -148,7 +152,7 @@ class TakeoutHTMLParser(HTMLParser): def read_html(tpath: Path, file: str) -> Iterable[Parsed]: - results: List[Parsed] = [] + results: list[Parsed] = [] def cb(dt: datetime, url: Url, title: Title) -> None: results.append((dt, url, title)) parser = TakeoutHTMLParser(callback=cb) @@ -156,5 +160,3 @@ def read_html(tpath: Path, file: str) -> Iterable[Parsed]: data = fo.read() parser.feed(data) return results - -from ...core import __NOT_HPI_MODULE__ diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 170553a..80c2be1 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -14,24 +14,27 @@ the cachew cache REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +import os +from collections.abc import Sequence from contextlib import ExitStack from dataclasses import dataclass -import os -from typing import List, Sequence, cast from pathlib import Path -from my.core import make_config, stat, Stats, get_files, Paths, make_logger +from typing import cast + +from google_takeout_parser.parse_html.html_time_utils import ABBR_TIMEZONES + +from my.core import Paths, Stats, get_files, make_config, make_logger, stat from my.core.cachew import mcachew from my.core.error import ErrorPolicy from my.core.structure import match_structure - from my.core.time import user_forced -from google_takeout_parser.parse_html.html_time_utils import ABBR_TIMEZONES + ABBR_TIMEZONES.extend(user_forced()) import google_takeout_parser -from google_takeout_parser.path_dispatch import TakeoutParser -from google_takeout_parser.merge import GoogleEventSet, CacheResults +from google_takeout_parser.merge import CacheResults, GoogleEventSet from google_takeout_parser.models import BaseEvent +from google_takeout_parser.path_dispatch import TakeoutParser # see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example from my.config import google as user_config @@ -56,6 +59,7 @@ logger = make_logger(__name__, level="warning") # patch the takeout parser logger to match the computed loglevel from google_takeout_parser.log import setup as setup_takeout_logger + setup_takeout_logger(logger.level) @@ -83,7 +87,7 @@ except ImportError: google_takeout_version = str(getattr(google_takeout_parser, '__version__', 'unknown')) -def _cachew_depends_on() -> List[str]: +def _cachew_depends_on() -> list[str]: exports = sorted([str(p) for p in inputs()]) # add google takeout parser pip version to hash, so this re-creates on breaking changes exports.insert(0, f"google_takeout_version: {google_takeout_version}") diff --git a/my/google/takeout/paths.py b/my/google/takeout/paths.py index 948cf2e..6a523e2 100644 --- a/my/google/takeout/paths.py +++ b/my/google/takeout/paths.py @@ -2,13 +2,17 @@ Module for locating and accessing [[https://takeout.google.com][Google Takeout]] data ''' +from __future__ import annotations + +from my.core import __NOT_HPI_MODULE__ # isort: skip + from abc import abstractmethod +from collections.abc import Iterable from pathlib import Path -from typing import Iterable, Optional, Protocol from more_itertools import last -from my.core import __NOT_HPI_MODULE__, Paths, get_files +from my.core import Paths, get_files class config: @@ -33,7 +37,7 @@ def make_config() -> config: return combined_config() -def get_takeouts(*, path: Optional[str] = None) -> Iterable[Path]: +def get_takeouts(*, path: str | None = None) -> Iterable[Path]: """ Sometimes google splits takeout into multiple archives, so we need to detect the ones that contain the path we need """ @@ -45,7 +49,7 @@ def get_takeouts(*, path: Optional[str] = None) -> Iterable[Path]: yield takeout -def get_last_takeout(*, path: Optional[str] = None) -> Optional[Path]: +def get_last_takeout(*, path: str | None = None) -> Path | None: return last(get_takeouts(path=path), default=None) diff --git a/my/hackernews/dogsheep.py b/my/hackernews/dogsheep.py index de6c58d..8303284 100644 --- a/my/hackernews/dogsheep.py +++ b/my/hackernews/dogsheep.py @@ -3,14 +3,14 @@ Hackernews data via Dogsheep [[hacker-news-to-sqlite][https://github.com/dogshee """ from __future__ import annotations +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Sequence, Optional -from my.core import get_files, Paths, Res, datetime_aware -from my.core.sqlite import sqlite_connection import my.config +from my.core import Paths, Res, datetime_aware, get_files +from my.core.sqlite import sqlite_connection from .common import hackernews_link @@ -33,9 +33,9 @@ class Item: id: str type: str created: datetime_aware # checked and it's utc - title: Optional[str] # only present for Story - text_html: Optional[str] # should be present for Comment and might for Story - url: Optional[str] # might be present for Story + title: str | None # only present for Story + text_html: str | None # should be present for Comment and might for Story + url: str | None # might be present for Story # todo process 'deleted'? fields? # todo process 'parent'? diff --git a/my/hackernews/harmonic.py b/my/hackernews/harmonic.py index 3b4ae61..08a82e6 100644 --- a/my/hackernews/harmonic.py +++ b/my/hackernews/harmonic.py @@ -1,17 +1,22 @@ """ [[https://play.google.com/store/apps/details?id=com.simon.harmonichackernews][Harmonic]] app for Hackernews """ + +from __future__ import annotations + REQUIRES = ['lxml', 'orjson'] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone -import orjson from pathlib import Path -from typing import Any, Dict, Iterator, List, Optional, Sequence, TypedDict, cast +from typing import Any, TypedDict, cast +import orjson from lxml import etree from more_itertools import one +import my.config from my.core import ( Paths, Res, @@ -22,8 +27,10 @@ from my.core import ( stat, ) from my.core.common import unique_everseen -import my.config -from .common import hackernews_link, SavedBase + +from .common import SavedBase, hackernews_link + +import my.config # isort: skip logger = make_logger(__name__) @@ -43,7 +50,7 @@ class Cached(TypedDict): created_at_i: int id: str points: int - test: Optional[str] + test: str | None title: str type: str # TODO Literal['story', 'comment']? comments are only in 'children' field tho url: str @@ -94,16 +101,16 @@ def _saved() -> Iterator[Res[Saved]]: # TODO defensive for each item! tr = etree.parse(path) - res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORIES_STRINGS"]'))) + res = one(cast(list[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORIES_STRINGS"]'))) cached_ids = [x.text.split('-')[0] for x in res] - cached: Dict[str, Cached] = {} + cached: dict[str, Cached] = {} for sid in cached_ids: - res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORY{sid}"]'))) + res = one(cast(list[Any], tr.xpath(f'//*[@name="{_PREFIX}_CACHED_STORY{sid}"]'))) j = orjson.loads(res.text) cached[sid] = j - res = one(cast(List[Any], tr.xpath(f'//*[@name="{_PREFIX}_BOOKMARKS"]'))) + res = one(cast(list[Any], tr.xpath(f'//*[@name="{_PREFIX}_BOOKMARKS"]'))) for x in res.text.split('-'): ids, item_timestamp = x.split('q') # not sure if timestamp is any useful? diff --git a/my/hackernews/materialistic.py b/my/hackernews/materialistic.py index 4d5cd47..ccf285b 100644 --- a/my/hackernews/materialistic.py +++ b/my/hackernews/materialistic.py @@ -1,19 +1,20 @@ """ [[https://play.google.com/store/apps/details?id=io.github.hidroh.materialistic][Materialistic]] app for Hackernews """ +from collections.abc import Iterator, Sequence from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, Iterator, NamedTuple, Sequence +from typing import Any, NamedTuple from more_itertools import unique_everseen -from my.core import get_files, datetime_aware, make_logger +from my.core import datetime_aware, get_files, make_logger from my.core.sqlite import sqlite_connection -from my.config import materialistic as config # todo migrate config to my.hackernews.materialistic - from .common import hackernews_link +# todo migrate config to my.hackernews.materialistic +from my.config import materialistic as config # isort: skip logger = make_logger(__name__) @@ -22,7 +23,7 @@ def inputs() -> Sequence[Path]: return get_files(config.export_path) -Row = Dict[str, Any] +Row = dict[str, Any] class Saved(NamedTuple): diff --git a/my/hypothesis.py b/my/hypothesis.py index 82104cd..15e854b 100644 --- a/my/hypothesis.py +++ b/my/hypothesis.py @@ -4,20 +4,22 @@ REQUIRES = [ 'git+https://github.com/karlicoss/hypexport', ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Iterator, Sequence, TYPE_CHECKING +from typing import TYPE_CHECKING from my.core import ( - get_files, - stat, Paths, Res, Stats, + get_files, + stat, ) from my.core.cfg import make_config from my.core.hpi_compat import always_supports_sequence -import my.config + +import my.config # isort: skip @dataclass diff --git a/my/instagram/all.py b/my/instagram/all.py index 8007399..214e6ac 100644 --- a/my/instagram/all.py +++ b/my/instagram/all.py @@ -1,11 +1,10 @@ -from typing import Iterator +from collections.abc import Iterator -from my.core import Res, stat, Stats +from my.core import Res, Stats, stat from my.core.source import import_source from .common import Message, _merge_messages - src_gdpr = import_source(module_name='my.instagram.gdpr') @src_gdpr def _messages_gdpr() -> Iterator[Res[Message]]: diff --git a/my/instagram/android.py b/my/instagram/android.py index 96b75d2..12c11d3 100644 --- a/my/instagram/android.py +++ b/my/instagram/android.py @@ -3,30 +3,29 @@ Bumble data from Android app database (in =/data/data/com.instagram.android/data """ from __future__ import annotations +import json +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime -import json from pathlib import Path -import sqlite3 -from typing import Iterator, Sequence, Optional, Dict, Union from my.core import ( - get_files, - Paths, - make_config, - make_logger, - datetime_naive, Json, + Paths, Res, assert_never, + datetime_naive, + get_files, + make_config, + make_logger, ) -from my.core.common import unique_everseen from my.core.cachew import mcachew +from my.core.common import unique_everseen from my.core.error import echain -from my.core.sqlite import sqlite_connect_immutable, select - -from my.config import instagram as user_config +from my.core.sqlite import select, sqlite_connect_immutable +from my.config import instagram as user_config # isort: skip logger = make_logger(__name__) @@ -38,8 +37,8 @@ class instagram_android_config(user_config.android): # sadly doesn't seem easy to extract user's own handle/name from the db... # todo maybe makes more sense to keep in parent class? not sure... - username: Optional[str] = None - full_name: Optional[str] = None + username: str | None = None + full_name: str | None = None config = make_config(instagram_android_config) @@ -101,13 +100,13 @@ class MessageError(RuntimeError): return self.rest == other.rest -def _parse_message(j: Json) -> Optional[_Message]: +def _parse_message(j: Json) -> _Message | None: id = j['item_id'] t = j['item_type'] tid = j['thread_key']['thread_id'] uid = j['user_id'] created = datetime.fromtimestamp(int(j['timestamp']) / 1_000_000) - text: Optional[str] = None + text: str | None = None if t == 'text': text = j['text'] elif t == 'reel_share': @@ -133,7 +132,7 @@ def _parse_message(j: Json) -> Optional[_Message]: ) -def _process_db(db: sqlite3.Connection) -> Iterator[Res[Union[User, _Message]]]: +def _process_db(db: sqlite3.Connection) -> Iterator[Res[User | _Message]]: # TODO ugh. seems like no way to extract username? # sometimes messages (e.g. media_share) contain it in message field # but generally it's not present. ugh @@ -175,7 +174,7 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Res[Union[User, _Message]]]: yield e -def _entities() -> Iterator[Res[Union[User, _Message]]]: +def _entities() -> Iterator[Res[User | _Message]]: # NOTE: definitely need to merge multiple, app seems to recycle old messages # TODO: hmm hard to guarantee timestamp ordering when we use synthetic input data... # todo use TypedDict? @@ -194,7 +193,7 @@ def _entities() -> Iterator[Res[Union[User, _Message]]]: @mcachew(depends_on=inputs) def messages() -> Iterator[Res[Message]]: - id2user: Dict[str, User] = {} + id2user: dict[str, User] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x diff --git a/my/instagram/common.py b/my/instagram/common.py index 4df07a1..17d130f 100644 --- a/my/instagram/common.py +++ b/my/instagram/common.py @@ -1,9 +1,10 @@ +from collections.abc import Iterator from dataclasses import replace from datetime import datetime from itertools import chain -from typing import Iterator, Dict, Any, Protocol +from typing import Any, Protocol -from my.core import warn_if_empty, Res +from my.core import Res, warn_if_empty class User(Protocol): @@ -40,7 +41,7 @@ def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]: # ugh. seems that GDPR thread ids are completely uncorrelated to any android ids (tried searching over all sqlite dump) # so the only way to correlate is to try and match messages # we also can't use unique_everseen here, otherwise will never get a chance to unify threads - mmap: Dict[str, Message] = {} + mmap: dict[str, Message] = {} thread_map = {} user_map = {} @@ -60,7 +61,7 @@ def _merge_messages(*sources: Iterator[Res[Message]]) -> Iterator[Res[Message]]: user_map[m.user.id] = mm.user else: # not emitted yet, need to emit - repls: Dict[str, Any] = {} + repls: dict[str, Any] = {} tid = thread_map.get(m.thread_id) if tid is not None: repls['thread_id'] = tid diff --git a/my/instagram/gdpr.py b/my/instagram/gdpr.py index 1415d55..7454a04 100644 --- a/my/instagram/gdpr.py +++ b/my/instagram/gdpr.py @@ -2,26 +2,27 @@ Instagram data (uses [[https://www.instagram.com/download/request][official GDPR export]]) """ +from __future__ import annotations + +import json +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime -import json from pathlib import Path -from typing import Iterator, Sequence, Dict, Union from more_itertools import bucket from my.core import ( - get_files, Paths, - datetime_naive, Res, assert_never, + datetime_naive, + get_files, make_logger, ) from my.core.common import unique_everseen -from my.config import instagram as user_config - +from my.config import instagram as user_config # isort: skip logger = make_logger(__name__) @@ -70,7 +71,7 @@ def _decode(s: str) -> str: return s.encode('latin-1').decode('utf8') -def _entities() -> Iterator[Res[Union[User, _Message]]]: +def _entities() -> Iterator[Res[User | _Message]]: # it's worth processing all previous export -- sometimes instagram removes some metadata from newer ones # NOTE: here there are basically two options # - process inputs as is (from oldest to newest) @@ -84,7 +85,7 @@ def _entities() -> Iterator[Res[Union[User, _Message]]]: yield from _entitites_from_path(path) -def _entitites_from_path(path: Path) -> Iterator[Res[Union[User, _Message]]]: +def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]: # TODO make sure it works both with plan directory # idelaly get_files should return the right thing, and we won't have to force ZipPath/match_structure here # e.g. possible options are: @@ -202,7 +203,7 @@ def _entitites_from_path(path: Path) -> Iterator[Res[Union[User, _Message]]]: # TODO basically copy pasted from android.py... hmm def messages() -> Iterator[Res[Message]]: - id2user: Dict[str, User] = {} + id2user: dict[str, User] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x diff --git a/my/instapaper.py b/my/instapaper.py index df1f70b..d79e7e4 100644 --- a/my/instapaper.py +++ b/my/instapaper.py @@ -7,10 +7,10 @@ REQUIRES = [ from dataclasses import dataclass -from .core import Paths - from my.config import instapaper as user_config +from .core import Paths + @dataclass class instapaper(user_config): @@ -22,6 +22,7 @@ class instapaper(user_config): from .core.cfg import make_config + config = make_config(instapaper) @@ -39,9 +40,12 @@ Bookmark = dal.Bookmark Page = dal.Page -from typing import Sequence, Iterable +from collections.abc import Iterable, Sequence from pathlib import Path + from .core import get_files + + def inputs() -> Sequence[Path]: return get_files(config.export_path) diff --git a/my/ip/all.py b/my/ip/all.py index 46c1fec..e8277c1 100644 --- a/my/ip/all.py +++ b/my/ip/all.py @@ -9,10 +9,9 @@ For an example of how this could be used, see https://github.com/seanbreckenridg REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] -from typing import Iterator +from collections.abc import Iterator from my.core import Stats, warn_if_empty - from my.ip.common import IP diff --git a/my/ip/common.py b/my/ip/common.py index 244ddc5..ef54ee3 100644 --- a/my/ip/common.py +++ b/my/ip/common.py @@ -2,11 +2,12 @@ Provides location/timezone data from IP addresses, using [[https://github.com/seanbreckenridge/ipgeocache][ipgeocache]] """ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip import ipaddress -from typing import NamedTuple, Iterator, Tuple +from collections.abc import Iterator from datetime import datetime +from typing import NamedTuple import ipgeocache @@ -22,7 +23,7 @@ class IP(NamedTuple): return ipgeocache.get(self.addr) @property - def latlon(self) -> Tuple[float, float]: + def latlon(self) -> tuple[float, float]: loc: str = self.ipgeocache()["loc"] lat, _, lon = loc.partition(",") return float(lat), float(lon) diff --git a/my/jawbone/__init__.py b/my/jawbone/__init__.py index 35112ba..463d735 100644 --- a/my/jawbone/__init__.py +++ b/my/jawbone/__init__.py @@ -1,10 +1,11 @@ from __future__ import annotations -from typing import Dict, Any, List, Iterable import json +from collections.abc import Iterable +from datetime import date, datetime, time, timedelta from functools import lru_cache -from datetime import datetime, date, time, timedelta from pathlib import Path +from typing import Any import pytz @@ -14,7 +15,6 @@ logger = make_logger(__name__) from my.config import jawbone as config # type: ignore[attr-defined] - BDIR = config.export_dir PHASES_FILE = BDIR / 'phases.json' SLEEPS_FILE = BDIR / 'sleeps.json' @@ -24,7 +24,7 @@ GRAPHS_DIR = BDIR / 'graphs' XID = str # TODO how to shared with backup thing? -Phases = Dict[XID, Any] +Phases = dict[XID, Any] @lru_cache(1) def get_phases() -> Phases: return json.loads(PHASES_FILE.read_text()) @@ -89,7 +89,7 @@ class SleepEntry: # TODO might be useful to cache these?? @property - def phases(self) -> List[datetime]: + def phases(self) -> list[datetime]: # TODO make sure they are consistent with emfit? return [self._fromts(i['time']) for i in get_phases()[self.xid]] @@ -100,12 +100,13 @@ class SleepEntry: return str(self) -def load_sleeps() -> List[SleepEntry]: +def load_sleeps() -> list[SleepEntry]: sleeps = json.loads(SLEEPS_FILE.read_text()) return [SleepEntry(js) for js in sleeps] -from ..core.error import Res, set_error_datetime, extract_error_datetime +from ..core.error import Res, extract_error_datetime, set_error_datetime + def pre_dataframe() -> Iterable[Res[SleepEntry]]: from more_itertools import bucket @@ -129,9 +130,9 @@ def pre_dataframe() -> Iterable[Res[SleepEntry]]: def dataframe(): - dicts: List[Dict[str, Any]] = [] + dicts: list[dict[str, Any]] = [] for s in pre_dataframe(): - d: Dict[str, Any] + d: dict[str, Any] if isinstance(s, Exception): dt = extract_error_datetime(s) d = { @@ -181,7 +182,7 @@ def plot_one(sleep: SleepEntry, fig, axes, xlims=None, *, showtext=True): print(f"{sleep.xid} span: {span}") # pip install imageio - from imageio import imread # type: ignore + from imageio import imread # type: ignore img = imread(sleep.graph) # all of them are 300x300 images apparently @@ -260,8 +261,8 @@ def predicate(sleep: SleepEntry): # TODO move to dashboard def plot() -> None: - from matplotlib.figure import Figure # type: ignore[import-not-found] import matplotlib.pyplot as plt # type: ignore[import-not-found] + from matplotlib.figure import Figure # type: ignore[import-not-found] # TODO FIXME melatonin data melatonin_data = {} # type: ignore[var-annotated] diff --git a/my/jawbone/plots.py b/my/jawbone/plots.py index d26d606..5968412 100755 --- a/my/jawbone/plots.py +++ b/my/jawbone/plots.py @@ -1,10 +1,11 @@ #!/usr/bin/env python3 # TODO this should be in dashboard -from pathlib import Path # from kython.plotting import * from csv import DictReader +from pathlib import Path +from typing import Any, NamedTuple -from typing import Dict, Any, NamedTuple +import matplotlib.pylab as pylab # type: ignore # sleep = [] # with open('2017.csv', 'r') as fo: @@ -12,16 +13,14 @@ from typing import Dict, Any, NamedTuple # for line in islice(reader, 0, 10): # sleep # print(line) - -import matplotlib.pyplot as plt # type: ignore +import matplotlib.pyplot as plt # type: ignore from numpy import genfromtxt -import matplotlib.pylab as pylab # type: ignore pylab.rcParams['figure.figsize'] = (32.0, 24.0) pylab.rcParams['font.size'] = 10 jawboneDataFeatures = Path(__file__).parent / 'features.csv' # Data File Path -featureDesc: Dict[str, str] = {} +featureDesc: dict[str, str] = {} for x in genfromtxt(jawboneDataFeatures, dtype='unicode', delimiter=','): featureDesc[x[0]] = x[1] @@ -52,7 +51,7 @@ class SleepData(NamedTuple): quality: float # ??? @classmethod - def from_jawbone_dict(cls, d: Dict[str, Any]): + def from_jawbone_dict(cls, d: dict[str, Any]): return cls( date=d['DATE'], asleep_time=_safe_mins(_safe_float(d['s_asleep_time'])), @@ -75,7 +74,7 @@ class SleepData(NamedTuple): def iter_useful(data_file: str): - with open(data_file) as fo: + with Path(data_file).open() as fo: reader = DictReader(fo) for d in reader: dt = SleepData.from_jawbone_dict(d) @@ -95,6 +94,7 @@ files = [ ] from kython import concat, parse_date # type: ignore + useful = concat(*(list(iter_useful(str(f))) for f in files)) # for u in useful: @@ -108,6 +108,7 @@ dates = [parse_date(u.date, yearfirst=True, dayfirst=False) for u in useful] # TODO don't need this anymore? it's gonna be in dashboards package from kython.plotting import plot_timestamped # type: ignore + for attr, lims, mavg, fig in [ ('light', (0, 400), 5, None), ('deep', (0, 600), 5, None), diff --git a/my/kobo.py b/my/kobo.py index 85bc50f..b4a1575 100644 --- a/my/kobo.py +++ b/my/kobo.py @@ -7,21 +7,22 @@ REQUIRES = [ 'kobuddy', ] +from collections.abc import Iterator from dataclasses import dataclass -from typing import Iterator - -from my.core import ( - get_files, - stat, - Paths, - Stats, -) -from my.core.cfg import make_config -import my.config import kobuddy -from kobuddy import Highlight, get_highlights from kobuddy import * +from kobuddy import Highlight, get_highlights + +from my.core import ( + Paths, + Stats, + get_files, + stat, +) +from my.core.cfg import make_config + +import my.config # isort: skip @dataclass @@ -51,7 +52,7 @@ def stats() -> Stats: ## TODO hmm. not sure if all this really belongs here?... perhaps orger? -from typing import Callable, Union, List +from typing import Callable, Union # TODO maybe type over T? _Predicate = Callable[[str], bool] @@ -69,17 +70,17 @@ def from_predicatish(p: Predicatish) -> _Predicate: return p -def by_annotation(predicatish: Predicatish, **kwargs) -> List[Highlight]: +def by_annotation(predicatish: Predicatish, **kwargs) -> list[Highlight]: pred = from_predicatish(predicatish) - res: List[Highlight] = [] + res: list[Highlight] = [] for h in get_highlights(**kwargs): if pred(h.annotation): res.append(h) return res -def get_todos() -> List[Highlight]: +def get_todos() -> list[Highlight]: def with_todo(ann): if ann is None: ann = '' diff --git a/my/kython/kompress.py b/my/kython/kompress.py index 01e24e4..a5d9c29 100644 --- a/my/kython/kompress.py +++ b/my/kython/kompress.py @@ -1,5 +1,4 @@ -from my.core import __NOT_HPI_MODULE__ -from my.core import warnings +from my.core import __NOT_HPI_MODULE__, warnings warnings.high('my.kython.kompress is deprecated, please use "kompress" library directly. See https://github.com/karlicoss/kompress') diff --git a/my/lastfm.py b/my/lastfm.py index d20ebf3..cd9fa8b 100644 --- a/my/lastfm.py +++ b/my/lastfm.py @@ -3,9 +3,9 @@ Last.fm scrobbles ''' from dataclasses import dataclass -from my.core import Paths, Json, make_logger, get_files -from my.config import lastfm as user_config +from my.config import lastfm as user_config +from my.core import Json, Paths, get_files, make_logger logger = make_logger(__name__) @@ -19,13 +19,15 @@ class lastfm(user_config): from my.core.cfg import make_config + config = make_config(lastfm) -from datetime import datetime, timezone import json +from collections.abc import Iterable, Sequence +from datetime import datetime, timezone from pathlib import Path -from typing import NamedTuple, Sequence, Iterable +from typing import NamedTuple from my.core.cachew import mcachew @@ -76,7 +78,9 @@ def scrobbles() -> Iterable[Scrobble]: yield Scrobble(raw=raw) -from my.core import stat, Stats +from my.core import Stats, stat + + def stats() -> Stats: return stat(scrobbles) diff --git a/my/location/all.py b/my/location/all.py index fd88721..c6e8cab 100644 --- a/my/location/all.py +++ b/my/location/all.py @@ -2,14 +2,13 @@ Merges location data from multiple sources """ -from typing import Iterator +from collections.abc import Iterator -from my.core import Stats, LazyLogger +from my.core import LazyLogger, Stats from my.core.source import import_source from .common import Location - logger = LazyLogger(__name__, level="warning") diff --git a/my/location/common.py b/my/location/common.py index f406370..4c47ef0 100644 --- a/my/location/common.py +++ b/my/location/common.py @@ -1,12 +1,13 @@ -from datetime import date, datetime -from typing import Union, Tuple, Optional, Iterable, TextIO, Iterator, Protocol -from dataclasses import dataclass +from my.core import __NOT_HPI_MODULE__ # isort: skip -from my.core import __NOT_HPI_MODULE__ +from collections.abc import Iterable, Iterator +from dataclasses import dataclass +from datetime import date, datetime +from typing import Optional, Protocol, TextIO, Union DateIsh = Union[datetime, date, str] -LatLon = Tuple[float, float] +LatLon = tuple[float, float] class LocationProtocol(Protocol): diff --git a/my/location/fallback/all.py b/my/location/fallback/all.py index a5daa05..d340148 100644 --- a/my/location/fallback/all.py +++ b/my/location/fallback/all.py @@ -1,14 +1,16 @@ # TODO: add config here which passes kwargs to estimate_from (under_accuracy) # overwritable by passing the kwarg name here to the top-level estimate_location -from typing import Iterator, Optional +from __future__ import annotations + +from collections.abc import Iterator from my.core.source import import_source from my.location.fallback.common import ( - estimate_from, - FallbackLocation, DateExact, + FallbackLocation, LocationEstimator, + estimate_from, ) @@ -24,7 +26,7 @@ def fallback_estimators() -> Iterator[LocationEstimator]: yield _home_estimate -def estimate_location(dt: DateExact, *, first_match: bool=False, under_accuracy: Optional[int] = None) -> FallbackLocation: +def estimate_location(dt: DateExact, *, first_match: bool=False, under_accuracy: int | None = None) -> FallbackLocation: loc = estimate_from(dt, estimators=list(fallback_estimators()), first_match=first_match, under_accuracy=under_accuracy) # should never happen if the user has home configured if loc is None: diff --git a/my/location/fallback/common.py b/my/location/fallback/common.py index 13bc603..622b2f5 100644 --- a/my/location/fallback/common.py +++ b/my/location/fallback/common.py @@ -1,9 +1,12 @@ from __future__ import annotations -from dataclasses import dataclass -from typing import Optional, Callable, Sequence, Iterator, List, Union -from datetime import datetime, timedelta, timezone -from ..common import LocationProtocol, Location +from collections.abc import Iterator, Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from typing import Callable, Union + +from ..common import Location, LocationProtocol + DateExact = Union[datetime, float, int] # float/int as epoch timestamps Second = float @@ -13,10 +16,10 @@ class FallbackLocation(LocationProtocol): lat: float lon: float dt: datetime - duration: Optional[Second] = None - accuracy: Optional[float] = None - elevation: Optional[float] = None - datasource: Optional[str] = None # which module provided this, useful for debugging + duration: Second | None = None + accuracy: float | None = None + elevation: float | None = None + datasource: str | None = None # which module provided this, useful for debugging def to_location(self, *, end: bool = False) -> Location: ''' @@ -43,9 +46,9 @@ class FallbackLocation(LocationProtocol): lon: float, dt: datetime, end_dt: datetime, - accuracy: Optional[float] = None, - elevation: Optional[float] = None, - datasource: Optional[str] = None, + accuracy: float | None = None, + elevation: float | None = None, + datasource: str | None = None, ) -> FallbackLocation: ''' Create FallbackLocation from a start date and an end date @@ -93,13 +96,13 @@ def estimate_from( estimators: LocationEstimators, *, first_match: bool = False, - under_accuracy: Optional[int] = None, -) -> Optional[FallbackLocation]: + under_accuracy: int | None = None, +) -> FallbackLocation | None: ''' first_match: if True, return the first location found under_accuracy: if set, only return locations with accuracy under this value ''' - found: List[FallbackLocation] = [] + found: list[FallbackLocation] = [] for loc in _iter_estimate_from(dt, estimators): if under_accuracy is not None and loc.accuracy is not None and loc.accuracy > under_accuracy: continue diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py index e44c59d..f88fee0 100644 --- a/my/location/fallback/via_home.py +++ b/my/location/fallback/via_home.py @@ -2,25 +2,22 @@ Simple location provider, serving as a fallback when more detailed data isn't available ''' +from __future__ import annotations + +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, time, timezone -from functools import lru_cache -from typing import Sequence, Tuple, Union, cast, List, Iterator +from functools import cache +from typing import cast from my.config import location as user_config +from my.location.common import DateIsh, LatLon +from my.location.fallback.common import DateExact, FallbackLocation -from my.location.common import LatLon, DateIsh -from my.location.fallback.common import FallbackLocation, DateExact @dataclass class Config(user_config): - home: Union[ - LatLon, # either single, 'current' location - Sequence[Tuple[ # or, a sequence of location history - DateIsh, # date when you moved to - LatLon, # the location - ]] - ] + home: LatLon | Sequence[tuple[DateIsh, LatLon]] # default ~30km accuracy # this is called 'home_accuracy' since it lives on the base location.config object, @@ -29,13 +26,13 @@ class Config(user_config): # TODO could make current Optional and somehow determine from system settings? @property - def _history(self) -> Sequence[Tuple[datetime, LatLon]]: + def _history(self) -> Sequence[tuple[datetime, LatLon]]: home1 = self.home # todo ugh, can't test for isnstance LatLon, it's a tuple itself - home2: Sequence[Tuple[DateIsh, LatLon]] + home2: Sequence[tuple[DateIsh, LatLon]] if isinstance(home1[0], tuple): # already a sequence - home2 = cast(Sequence[Tuple[DateIsh, LatLon]], home1) + home2 = cast(Sequence[tuple[DateIsh, LatLon]], home1) else: # must be a pair of coordinates. also doesn't really matter which date to pick? loc = cast(LatLon, home1) @@ -60,10 +57,11 @@ class Config(user_config): from ...core.cfg import make_config + config = make_config(Config) -@lru_cache(maxsize=None) +@cache def get_location(dt: datetime) -> LatLon: ''' Interpolates the location at dt @@ -74,8 +72,8 @@ def get_location(dt: datetime) -> LatLon: # TODO: in python3.8, use functools.cached_property instead? -@lru_cache(maxsize=None) -def homes_cached() -> List[Tuple[datetime, LatLon]]: +@cache +def homes_cached() -> list[tuple[datetime, LatLon]]: return list(config._history) diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index 79a452c..732af67 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -7,8 +7,8 @@ REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] from dataclasses import dataclass from datetime import timedelta -from my.core import Stats, make_config from my.config import location +from my.core import Stats, make_config from my.core.warnings import medium @@ -24,13 +24,13 @@ class ip_config(location.via_ip): config = make_config(ip_config) +from collections.abc import Iterator from functools import lru_cache -from typing import Iterator, List from my.core import make_logger from my.core.compat import bisect_left from my.location.common import Location -from my.location.fallback.common import FallbackLocation, DateExact, _datetime_timestamp +from my.location.fallback.common import DateExact, FallbackLocation, _datetime_timestamp logger = make_logger(__name__, level="warning") @@ -60,7 +60,7 @@ def locations() -> Iterator[Location]: @lru_cache(1) -def _sorted_fallback_locations() -> List[FallbackLocation]: +def _sorted_fallback_locations() -> list[FallbackLocation]: fl = list(filter(lambda l: l.duration is not None, fallback_locations())) logger.debug(f"Fallback locations: {len(fl)}, sorting...:") fl.sort(key=lambda l: l.dt.timestamp()) diff --git a/my/location/google.py b/my/location/google.py index b966ec6..750c847 100644 --- a/my/location/google.py +++ b/my/location/google.py @@ -3,28 +3,27 @@ Location data from Google Takeout DEPRECATED: setup my.google.takeout.parser and use my.location.google_takeout instead """ +from __future__ import annotations REQUIRES = [ 'geopy', # checking that coordinates are valid 'ijson', ] +import re +from collections.abc import Iterable, Sequence from datetime import datetime, timezone from itertools import islice from pathlib import Path -from subprocess import Popen, PIPE -from typing import Iterable, NamedTuple, Optional, Sequence, IO, Tuple -import re +from subprocess import PIPE, Popen +from typing import IO, NamedTuple, Optional # pip3 install geopy -import geopy # type: ignore +import geopy # type: ignore -from my.core import stat, Stats, make_logger +from my.core import Stats, make_logger, stat, warnings from my.core.cachew import cache_dir, mcachew -from my.core import warnings - - warnings.high("Please set up my.google.takeout.parser module for better takeout support") @@ -43,7 +42,7 @@ class Location(NamedTuple): alt: Optional[float] -TsLatLon = Tuple[int, int, int] +TsLatLon = tuple[int, int, int] def _iter_via_ijson(fo) -> Iterable[TsLatLon]: @@ -51,10 +50,10 @@ def _iter_via_ijson(fo) -> Iterable[TsLatLon]: # todo extract to common? try: # pip3 install ijson cffi - import ijson.backends.yajl2_cffi as ijson # type: ignore + import ijson.backends.yajl2_cffi as ijson # type: ignore except: warnings.medium("Falling back to default ijson because 'cffi' backend isn't found. It's up to 2x faster, you might want to check it out") - import ijson # type: ignore + import ijson # type: ignore for d in ijson.items(fo, 'locations.item'): yield ( diff --git a/my/location/google_takeout.py b/my/location/google_takeout.py index eb757ce..cb5bef3 100644 --- a/my/location/google_takeout.py +++ b/my/location/google_takeout.py @@ -4,13 +4,14 @@ Extracts locations using google_takeout_parser -- no shared code with the deprec REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] -from typing import Iterator +from collections.abc import Iterator -from my.google.takeout.parser import events, _cachew_depends_on from google_takeout_parser.models import Location as GoogleLocation -from my.core import stat, Stats, LazyLogger +from my.core import LazyLogger, Stats, stat from my.core.cachew import mcachew +from my.google.takeout.parser import _cachew_depends_on, events + from .common import Location logger = LazyLogger(__name__) diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index 5f2c055..7bddfa8 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -7,21 +7,24 @@ Extracts semantic location history using google_takeout_parser REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +from collections.abc import Iterator from dataclasses import dataclass -from typing import Iterator, List -from my.google.takeout.parser import events, _cachew_depends_on as _parser_cachew_depends_on from google_takeout_parser.models import PlaceVisit as SemanticLocation -from my.core import make_config, stat, LazyLogger, Stats +from my.core import LazyLogger, Stats, make_config, stat from my.core.cachew import mcachew from my.core.error import Res +from my.google.takeout.parser import _cachew_depends_on as _parser_cachew_depends_on +from my.google.takeout.parser import events + from .common import Location logger = LazyLogger(__name__) from my.config import location as user_config + @dataclass class semantic_locations_config(user_config.google_takeout_semantic): # a value between 0 and 100, 100 being the most confident @@ -36,7 +39,7 @@ config = make_config(semantic_locations_config) # add config to cachew dependency so it recomputes on config changes -def _cachew_depends_on() -> List[str]: +def _cachew_depends_on() -> list[str]: dep = _parser_cachew_depends_on() dep.insert(0, f"require_confidence={config.require_confidence} accuracy={config.accuracy}") return dep diff --git a/my/location/gpslogger.py b/my/location/gpslogger.py index 6d158a0..bbbf70e 100644 --- a/my/location/gpslogger.py +++ b/my/location/gpslogger.py @@ -20,20 +20,20 @@ class config(location.gpslogger): accuracy: float = 50.0 -from itertools import chain +from collections.abc import Iterator, Sequence from datetime import datetime, timezone +from itertools import chain from pathlib import Path -from typing import Iterator, Sequence, List import gpxpy from gpxpy.gpx import GPXXMLSyntaxException from more_itertools import unique_everseen -from my.core import Stats, LazyLogger +from my.core import LazyLogger, Stats from my.core.cachew import mcachew from my.core.common import get_files -from .common import Location +from .common import Location logger = LazyLogger(__name__, level="warning") @@ -49,7 +49,7 @@ def inputs() -> Sequence[Path]: return sorted(get_files(config.export_path, glob="*.gpx", sort=False), key=_input_sort_key) -def _cachew_depends_on() -> List[float]: +def _cachew_depends_on() -> list[float]: return [p.stat().st_mtime for p in inputs()] diff --git a/my/location/home.py b/my/location/home.py index f6e6978..c82dda7 100644 --- a/my/location/home.py +++ b/my/location/home.py @@ -1,7 +1,7 @@ -from .fallback.via_home import * - from my.core.warnings import high +from .fallback.via_home import * + high( "my.location.home is deprecated, use my.location.fallback.via_home instead, or estimate locations using the higher-level my.location.fallback.all.estimate_location" ) diff --git a/my/location/via_ip.py b/my/location/via_ip.py index df48f8b..d465ad0 100644 --- a/my/location/via_ip.py +++ b/my/location/via_ip.py @@ -1,7 +1,7 @@ REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] -from .fallback.via_ip import * - from my.core.warnings import high +from .fallback.via_ip import * + high("my.location.via_ip is deprecated, use my.location.fallback.via_ip instead") diff --git a/my/materialistic.py b/my/materialistic.py index 8a6a997..45af3f9 100644 --- a/my/materialistic.py +++ b/my/materialistic.py @@ -1,4 +1,5 @@ from .core.warnings import high + high("DEPRECATED! Please use my.hackernews.materialistic instead.") from .hackernews.materialistic import * diff --git a/my/media/imdb.py b/my/media/imdb.py index df31032..131f6a7 100644 --- a/my/media/imdb.py +++ b/my/media/imdb.py @@ -1,10 +1,12 @@ import csv +from collections.abc import Iterator from datetime import datetime -from typing import Iterator, List, NamedTuple +from typing import NamedTuple -from ..core import get_files +from my.core import get_files + +from my.config import imdb as config # isort: skip -from my.config import imdb as config def _get_last(): return max(get_files(config.export_path)) @@ -31,7 +33,7 @@ def iter_movies() -> Iterator[Movie]: yield Movie(created=created, title=title, rating=rating) -def get_movies() -> List[Movie]: +def get_movies() -> list[Movie]: return sorted(iter_movies(), key=lambda m: m.created) diff --git a/my/media/youtube.py b/my/media/youtube.py index 3ddbc14..9a38c43 100644 --- a/my/media/youtube.py +++ b/my/media/youtube.py @@ -1,4 +1,4 @@ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip from typing import TYPE_CHECKING diff --git a/my/monzo/monzoexport.py b/my/monzo/monzoexport.py index 3aa0cf5..f5e1cd1 100644 --- a/my/monzo/monzoexport.py +++ b/my/monzo/monzoexport.py @@ -5,16 +5,17 @@ REQUIRES = [ 'git+https://github.com/karlicoss/monzoexport', ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Sequence, Iterator from my.core import ( Paths, get_files, make_logger, ) -import my.config + +import my.config # isort: skip @dataclass diff --git a/my/orgmode.py b/my/orgmode.py index cf14e43..10f53c0 100644 --- a/my/orgmode.py +++ b/my/orgmode.py @@ -1,15 +1,17 @@ ''' Programmatic access and queries to org-mode files on the filesystem ''' +from __future__ import annotations REQUIRES = [ 'orgparse', ] import re +from collections.abc import Iterable, Sequence from datetime import datetime from pathlib import Path -from typing import Iterable, List, NamedTuple, Optional, Sequence, Tuple +from typing import NamedTuple, Optional import orgparse @@ -34,7 +36,7 @@ def make_config() -> config: class OrgNote(NamedTuple): created: Optional[datetime] heading: str - tags: List[str] + tags: list[str] def inputs() -> Sequence[Path]: @@ -45,7 +47,7 @@ def inputs() -> Sequence[Path]: _rgx = re.compile(orgparse.date.gene_timestamp_regex(brtype='inactive'), re.VERBOSE) -def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: +def _created(n: orgparse.OrgNode) -> tuple[datetime | None, str]: heading = n.heading # meh.. support in orgparse? pp = {} if n.is_root() else n.properties @@ -68,7 +70,7 @@ def _created(n: orgparse.OrgNode) -> Tuple[Optional[datetime], str]: def to_note(x: orgparse.OrgNode) -> OrgNote: # ugh. hack to merely make it cacheable heading = x.heading - created: Optional[datetime] + created: datetime | None try: c, heading = _created(x) if isinstance(c, datetime): diff --git a/my/pdfs.py b/my/pdfs.py index de9324d..eefd573 100644 --- a/my/pdfs.py +++ b/my/pdfs.py @@ -1,6 +1,7 @@ ''' PDF documents and annotations on your filesystem ''' +from __future__ import annotations as _annotations REQUIRES = [ 'git+https://github.com/0xabu/pdfannots', @@ -8,9 +9,10 @@ REQUIRES = [ ] import time +from collections.abc import Iterator, Sequence from datetime import datetime from pathlib import Path -from typing import Iterator, List, NamedTuple, Optional, Protocol, Sequence, TYPE_CHECKING +from typing import TYPE_CHECKING, NamedTuple, Optional, Protocol import pdfannots from more_itertools import bucket @@ -72,7 +74,7 @@ class Annotation(NamedTuple): created: Optional[datetime] # note: can be tz unaware in some bad pdfs... @property - def date(self) -> Optional[datetime]: + def date(self) -> datetime | None: # legacy name return self.created @@ -93,7 +95,7 @@ def _as_annotation(*, raw: pdfannots.Annotation, path: str) -> Annotation: ) -def get_annots(p: Path) -> List[Annotation]: +def get_annots(p: Path) -> list[Annotation]: b = time.time() with p.open('rb') as fo: doc = pdfannots.process_file(fo, emit_progress_to=None) @@ -150,17 +152,17 @@ class Pdf(NamedTuple): annotations: Sequence[Annotation] @property - def created(self) -> Optional[datetime]: + def created(self) -> datetime | None: annots = self.annotations return None if len(annots) == 0 else annots[-1].created @property - def date(self) -> Optional[datetime]: + def date(self) -> datetime | None: # legacy return self.created -def annotated_pdfs(*, filelist: Optional[Sequence[PathIsh]] = None) -> Iterator[Res[Pdf]]: +def annotated_pdfs(*, filelist: Sequence[PathIsh] | None = None) -> Iterator[Res[Pdf]]: if filelist is not None: # hacky... keeping it backwards compatible # https://github.com/karlicoss/HPI/pull/74 diff --git a/my/photos/main.py b/my/photos/main.py index bf912e4..f98cb15 100644 --- a/my/photos/main.py +++ b/my/photos/main.py @@ -1,27 +1,30 @@ """ Photos and videos on your filesystem, their GPS and timestamps """ + +from __future__ import annotations + REQUIRES = [ 'geopy', 'magic', ] # NOTE: also uses fdfind to search photos +import json +from collections.abc import Iterable, Iterator from concurrent.futures import ProcessPoolExecutor as Pool from datetime import datetime -import json from pathlib import Path -from typing import Optional, NamedTuple, Iterator, Iterable, List +from typing import NamedTuple, Optional from geopy.geocoders import Nominatim # type: ignore from my.core import LazyLogger -from my.core.error import Res, sort_res_by from my.core.cachew import cache_dir, mcachew +from my.core.error import Res, sort_res_by from my.core.mime import fastermime -from my.config import photos as config # type: ignore[attr-defined] - +from my.config import photos as config # type: ignore[attr-defined] # isort: skip logger = LazyLogger(__name__) @@ -55,15 +58,15 @@ class Photo(NamedTuple): return f'{config.base_url}{self._basename}' -from .utils import get_exif_from_file, ExifTags, Exif, dt_from_path, convert_ref +from .utils import Exif, ExifTags, convert_ref, dt_from_path, get_exif_from_file Result = Res[Photo] -def _make_photo_aux(*args, **kwargs) -> List[Result]: +def _make_photo_aux(*args, **kwargs) -> list[Result]: # for the process pool.. return list(_make_photo(*args, **kwargs)) -def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Iterator[Result]: +def _make_photo(photo: Path, mtype: str, *, parent_geo: LatLon | None) -> Iterator[Result]: exif: Exif if any(x in mtype for x in ['image/png', 'image/x-ms-bmp', 'video']): # TODO don't remember why.. @@ -77,7 +80,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Ite yield e exif = {} - def _get_geo() -> Optional[LatLon]: + def _get_geo() -> LatLon | None: meta = exif.get(ExifTags.GPSINFO, {}) if ExifTags.LAT in meta and ExifTags.LON in meta: return LatLon( @@ -87,7 +90,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Ite return parent_geo # TODO aware on unaware? - def _get_dt() -> Optional[datetime]: + def _get_dt() -> datetime | None: edt = exif.get(ExifTags.DATETIME, None) if edt is not None: dtimes = edt.replace(' 24', ' 00') # jeez maybe log it? @@ -123,7 +126,7 @@ def _make_photo(photo: Path, mtype: str, *, parent_geo: Optional[LatLon]) -> Ite def _candidates() -> Iterable[Res[str]]: # TODO that could be a bit slow if there are to many extra files? - from subprocess import Popen, PIPE + from subprocess import PIPE, Popen # TODO could extract this to common? # TODO would be nice to reuse get_files (or even let it use find) # that way would be easier to exclude @@ -162,7 +165,7 @@ def _photos(candidates: Iterable[Res[str]]) -> Iterator[Result]: from functools import lru_cache @lru_cache(None) - def get_geo(d: Path) -> Optional[LatLon]: + def get_geo(d: Path) -> LatLon | None: geof = d / 'geo.json' if not geof.exists(): if d == d.parent: @@ -214,5 +217,7 @@ def print_all() -> None: # todo cachew -- invalidate if function code changed? from ..core import Stats, stat + + def stats() -> Stats: return stat(photos) diff --git a/my/photos/utils.py b/my/photos/utils.py index c614c4a..e88def2 100644 --- a/my/photos/utils.py +++ b/my/photos/utils.py @@ -1,11 +1,13 @@ +from __future__ import annotations + +from ..core import __NOT_HPI_MODULE__ # isort: skip + from pathlib import Path -from typing import Dict import PIL.Image -from PIL.ExifTags import TAGS, GPSTAGS +from PIL.ExifTags import GPSTAGS, TAGS - -Exif = Dict +Exif = dict # TODO PIL.ExifTags.TAGS @@ -62,18 +64,15 @@ def convert_ref(cstr, ref: str) -> float: import re from datetime import datetime -from typing import Optional # TODO surely there is a library that does it?? # TODO this belongs to a private overlay or something # basically have a function that patches up dates after the files were yielded.. _DT_REGEX = re.compile(r'\D(\d{8})\D*(\d{6})\D') -def dt_from_path(p: Path) -> Optional[datetime]: +def dt_from_path(p: Path) -> datetime | None: name = p.stem mm = _DT_REGEX.search(name) if mm is None: return None dates = mm.group(1) + mm.group(2) return datetime.strptime(dates, "%Y%m%d%H%M%S") - -from ..core import __NOT_HPI_MODULE__ diff --git a/my/pinboard.py b/my/pinboard.py index ef4ca36..e98dc78 100644 --- a/my/pinboard.py +++ b/my/pinboard.py @@ -5,15 +5,16 @@ REQUIRES = [ 'git+https://github.com/karlicoss/pinbexport', ] +from collections.abc import Iterator, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Iterator, Sequence - -from my.core import get_files, Paths, Res -import my.config import pinbexport.dal as pinbexport +from my.core import Paths, Res, get_files + +import my.config # isort: skip + @dataclass class config(my.config.pinboard): # TODO rename to pinboard.pinbexport? diff --git a/my/pocket.py b/my/pocket.py index b638fba..ff9a788 100644 --- a/my/pocket.py +++ b/my/pocket.py @@ -7,10 +7,10 @@ REQUIRES = [ from dataclasses import dataclass from typing import TYPE_CHECKING -from .core import Paths - from my.config import pocket as user_config +from .core import Paths + @dataclass class pocket(user_config): @@ -23,6 +23,7 @@ class pocket(user_config): from .core.cfg import make_config + config = make_config(pocket) @@ -37,7 +38,7 @@ except ModuleNotFoundError as e: Article = dal.Article -from typing import Sequence, Iterable +from collections.abc import Iterable, Sequence # todo not sure if should be defensive against empty? @@ -51,9 +52,12 @@ def articles() -> Iterable[Article]: yield from _dal().articles() -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: from itertools import chain + from more_itertools import ilen return { **stat(articles), diff --git a/my/polar.py b/my/polar.py index e52bb14..2172014 100644 --- a/my/polar.py +++ b/my/polar.py @@ -1,11 +1,12 @@ """ [[https://github.com/burtonator/polar-bookshelf][Polar]] articles and highlights """ +from __future__ import annotations + from pathlib import Path -from typing import cast, TYPE_CHECKING +from typing import TYPE_CHECKING, cast - -import my.config +import my.config # isort: skip # todo use something similar to tz.via_location for config fallback if not TYPE_CHECKING: @@ -20,8 +21,11 @@ if user_config is None: pass -from .core import PathIsh from dataclasses import dataclass + +from .core import PathIsh + + @dataclass class polar(user_config): ''' @@ -32,20 +36,21 @@ class polar(user_config): from .core import make_config + config = make_config(polar) # todo not sure where it keeps stuff on Windows? # https://github.com/burtonator/polar-bookshelf/issues/296 -from datetime import datetime -from typing import List, Dict, Iterable, NamedTuple, Sequence, Optional import json +from collections.abc import Iterable, Sequence +from datetime import datetime +from typing import NamedTuple -from .core import LazyLogger, Json, Res +from .core import Json, LazyLogger, Res from .core.compat import fromisoformat from .core.error import echain, sort_res_by -from .core.konsume import wrap, Zoomable, Wdict - +from .core.konsume import Wdict, Zoomable, wrap logger = LazyLogger(__name__) @@ -65,7 +70,7 @@ class Highlight(NamedTuple): comments: Sequence[Comment] tags: Sequence[str] page: int # 1-indexed - color: Optional[str] = None + color: str | None = None Uid = str @@ -73,7 +78,7 @@ class Book(NamedTuple): created: datetime uid: Uid path: Path - title: Optional[str] + title: str | None # TODO hmmm. I think this needs to be defensive as well... # think about it later. items: Sequence[Highlight] @@ -129,7 +134,7 @@ class Loader: pi['dimensions'].consume_all() # TODO how to make it nicer? - cmap: Dict[Hid, List[Comment]] = {} + cmap: dict[Hid, list[Comment]] = {} vals = list(comments) for v in vals: cid = v['id'].zoom() @@ -163,7 +168,7 @@ class Loader: h['rects'].ignore() # TODO make it more generic.. - htags: List[str] = [] + htags: list[str] = [] if 'tags' in h: ht = h['tags'].zoom() for _k, v in list(ht.items()): @@ -242,7 +247,7 @@ def iter_entries() -> Iterable[Result]: yield err -def get_entries() -> List[Result]: +def get_entries() -> list[Result]: # sorting by first annotation is reasonable I guess??? # todo perhaps worth making it a pattern? X() returns iterable, get_X returns reasonably sorted list? return list(sort_res_by(iter_entries(), key=lambda e: e.created)) diff --git a/my/reddit/__init__.py b/my/reddit/__init__.py index e81aaf9..f344eeb 100644 --- a/my/reddit/__init__.py +++ b/my/reddit/__init__.py @@ -20,6 +20,7 @@ REQUIRES = [ from my.core.hpi_compat import handle_legacy_import + is_legacy_import = handle_legacy_import( parent_module_name=__name__, legacy_submodule_name='rexport', diff --git a/my/reddit/all.py b/my/reddit/all.py index daedba1..27e22df 100644 --- a/my/reddit/all.py +++ b/my/reddit/all.py @@ -1,8 +1,9 @@ -from typing import Iterator -from my.core import stat, Stats +from collections.abc import Iterator + +from my.core import Stats, stat from my.core.source import import_source -from .common import Save, Upvote, Comment, Submission, _merge_comments +from .common import Comment, Save, Submission, Upvote, _merge_comments # Man... ideally an all.py file isn't this verbose, but # reddit just feels like that much of a complicated source and diff --git a/my/reddit/common.py b/my/reddit/common.py index c01258b..40f9f6e 100644 --- a/my/reddit/common.py +++ b/my/reddit/common.py @@ -2,12 +2,14 @@ This defines Protocol classes, which make sure that each different type of shared models have a standardized interface """ -from my.core import __NOT_HPI_MODULE__ -from typing import Set, Iterator, Protocol +from my.core import __NOT_HPI_MODULE__ # isort: skip + +from collections.abc import Iterator from itertools import chain +from typing import Protocol -from my.core import datetime_aware, Json +from my.core import Json, datetime_aware # common fields across all the Protocol classes, so generic code can be written @@ -49,7 +51,7 @@ class Submission(RedditBase, Protocol): def _merge_comments(*sources: Iterator[Comment]) -> Iterator[Comment]: #from .rexport import logger #ignored = 0 - emitted: Set[str] = set() + emitted: set[str] = set() for e in chain(*sources): uid = e.id if uid in emitted: diff --git a/my/reddit/pushshift.py b/my/reddit/pushshift.py index 9580005..1bfa048 100644 --- a/my/reddit/pushshift.py +++ b/my/reddit/pushshift.py @@ -10,13 +10,13 @@ REQUIRES = [ from dataclasses import dataclass +# note: keeping pushshift import before config import, so it's handled gracefully by import_source +from pushshift_comment_export.dal import PComment, read_file + +from my.config import reddit as uconfig from my.core import Paths, Stats, stat from my.core.cfg import make_config -# note: keeping pushshift import before config import, so it's handled gracefully by import_source -from pushshift_comment_export.dal import read_file, PComment - -from my.config import reddit as uconfig @dataclass class pushshift_config(uconfig.pushshift): @@ -29,10 +29,10 @@ class pushshift_config(uconfig.pushshift): config = make_config(pushshift_config) -from my.core import get_files -from typing import Sequence, Iterator +from collections.abc import Iterator, Sequence from pathlib import Path +from my.core import get_files def inputs() -> Sequence[Path]: diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py index 5dcd7d9..cb6af01 100644 --- a/my/reddit/rexport.py +++ b/my/reddit/rexport.py @@ -7,23 +7,24 @@ REQUIRES = [ 'git+https://github.com/karlicoss/rexport', ] -from dataclasses import dataclass import inspect +from collections.abc import Iterator, Sequence +from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Iterator, Sequence +from typing import TYPE_CHECKING from my.core import ( - get_files, - make_logger, - warnings, - stat, Paths, Stats, + get_files, + make_logger, + stat, + warnings, ) from my.core.cachew import mcachew -from my.core.cfg import make_config, Attrs +from my.core.cfg import Attrs, make_config -from my.config import reddit as uconfig +from my.config import reddit as uconfig # isort: skip logger = make_logger(__name__) diff --git a/my/rescuetime.py b/my/rescuetime.py index 76a0d4c..0c9fd28 100644 --- a/my/rescuetime.py +++ b/my/rescuetime.py @@ -5,16 +5,15 @@ REQUIRES = [ 'git+https://github.com/karlicoss/rescuexport', ] -from pathlib import Path +from collections.abc import Iterable, Sequence from datetime import timedelta -from typing import Sequence, Iterable +from pathlib import Path -from my.core import get_files, make_logger, stat, Stats +from my.core import Stats, get_files, make_logger, stat from my.core.cachew import mcachew from my.core.error import Res, split_errors -from my.config import rescuetime as config - +from my.config import rescuetime as config # isort: skip logger = make_logger(__name__) @@ -24,6 +23,7 @@ def inputs() -> Sequence[Path]: import rescuexport.dal as dal + DAL = dal.DAL Entry = dal.Entry @@ -43,6 +43,8 @@ def groups(gap: timedelta=timedelta(hours=3)) -> Iterable[Res[Sequence[Entry]]]: # todo automatic dataframe interface? from .core.pandas import DataFrameT, as_dataframe + + def dataframe() -> DataFrameT: return as_dataframe(entries()) @@ -56,16 +58,19 @@ def stats() -> Stats: # basically, hack config and populate it with fake data? fake data generated by DAL, but the rest is handled by this? +from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterator + + # todo take seed, or what? @contextmanager def fake_data(rows: int=1000) -> Iterator: # todo also disable cachew automatically for such things? - from my.core.cfg import tmp_config - from my.core.cachew import disabled_cachew - from tempfile import TemporaryDirectory import json + from tempfile import TemporaryDirectory + + from my.core.cachew import disabled_cachew + from my.core.cfg import tmp_config with disabled_cachew(), TemporaryDirectory() as td: tdir = Path(td) f = tdir / 'rescuetime.json' diff --git a/my/roamresearch.py b/my/roamresearch.py index 2fe06d4..7322774 100644 --- a/my/roamresearch.py +++ b/my/roamresearch.py @@ -1,16 +1,19 @@ """ [[https://roamresearch.com][Roam]] data """ -from datetime import datetime, timezone -from pathlib import Path -from itertools import chain -import re -from typing import NamedTuple, Iterator, List, Optional +from __future__ import annotations -from .core import get_files, LazyLogger, Json +import re +from collections.abc import Iterator +from datetime import datetime, timezone +from itertools import chain +from pathlib import Path +from typing import NamedTuple from my.config import roamresearch as config +from .core import Json, LazyLogger, get_files + logger = LazyLogger(__name__) @@ -57,15 +60,15 @@ class Node(NamedTuple): return datetime.fromtimestamp(rt / 1000, tz=timezone.utc) @property - def title(self) -> Optional[str]: + def title(self) -> str | None: return self.raw.get(Keys.TITLE) @property - def body(self) -> Optional[str]: + def body(self) -> str | None: return self.raw.get(Keys.STRING) @property - def children(self) -> List['Node']: + def children(self) -> list[Node]: # TODO cache? needs a key argument (because of Json) ch = self.raw.get(Keys.CHILDREN, []) return list(map(Node, ch)) @@ -95,7 +98,7 @@ class Node(NamedTuple): # - heading -- notes that haven't been created yet return len(self.body or '') == 0 and len(self.children) == 0 - def traverse(self) -> Iterator['Node']: + def traverse(self) -> Iterator[Node]: # not sure about __iter__, because might be a bit unintuitive that it's recursive.. yield self for c in self.children: @@ -120,7 +123,7 @@ class Node(NamedTuple): return f'Node(created={self.created}, title={self.title}, body={self.body})' @staticmethod - def make(raw: Json) -> Iterator['Node']: + def make(raw: Json) -> Iterator[Node]: is_empty = set(raw.keys()) == {Keys.EDITED, Keys.EDIT_EMAIL, Keys.TITLE} # not sure about that... but daily notes end up like that if is_empty: @@ -130,11 +133,11 @@ class Node(NamedTuple): class Roam: - def __init__(self, raw: List[Json]) -> None: + def __init__(self, raw: list[Json]) -> None: self.raw = raw @property - def notes(self) -> List[Node]: + def notes(self) -> list[Node]: return list(chain.from_iterable(map(Node.make, self.raw))) def traverse(self) -> Iterator[Node]: diff --git a/my/rss/all.py b/my/rss/all.py index b4dbdbd..e10e4d2 100644 --- a/my/rss/all.py +++ b/my/rss/all.py @@ -3,9 +3,9 @@ Unified RSS data, merged from different services I used historically ''' # NOTE: you can comment out the sources you're not using -from . import feedbin, feedly +from collections.abc import Iterable -from typing import Iterable +from . import feedbin, feedly from .common import Subscription, compute_subscriptions diff --git a/my/rss/common.py b/my/rss/common.py index bb75297..bf9506e 100644 --- a/my/rss/common.py +++ b/my/rss/common.py @@ -1,10 +1,12 @@ -from my.core import __NOT_HPI_MODULE__ +from __future__ import annotations +from my.core import __NOT_HPI_MODULE__ # isort: skip + +from collections.abc import Iterable, Sequence from dataclasses import dataclass, replace from itertools import chain -from typing import Optional, List, Dict, Iterable, Tuple, Sequence -from my.core import warn_if_empty, datetime_aware +from my.core import datetime_aware, warn_if_empty @dataclass @@ -13,16 +15,16 @@ class Subscription: url: str id: str # TODO not sure about it... # eh, not all of them got reasonable 'created' time - created_at: Optional[datetime_aware] + created_at: datetime_aware | None subscribed: bool = True # snapshot of subscriptions at time -SubscriptionState = Tuple[datetime_aware, Sequence[Subscription]] +SubscriptionState = tuple[datetime_aware, Sequence[Subscription]] @warn_if_empty -def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscription]: +def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> list[Subscription]: """ Keeps track of everything I ever subscribed to. In addition, keeps track of unsubscribed as well (so you'd remember when and why you unsubscribed) @@ -30,7 +32,7 @@ def compute_subscriptions(*sources: Iterable[SubscriptionState]) -> List[Subscri states = list(chain.from_iterable(sources)) # TODO keep 'source'/'provider'/'service' attribute? - by_url: Dict[str, Subscription] = {} + by_url: dict[str, Subscription] = {} # ah. dates are used for sorting for _when, state in sorted(states): # TODO use 'when'? diff --git a/my/rss/feedbin.py b/my/rss/feedbin.py index dc13a17..5f4da0a 100644 --- a/my/rss/feedbin.py +++ b/my/rss/feedbin.py @@ -3,15 +3,15 @@ Feedbin RSS reader """ import json +from collections.abc import Iterator, Sequence from pathlib import Path -from typing import Iterator, Sequence -from my.core import get_files, stat, Stats +from my.core import Stats, get_files, stat from my.core.compat import fromisoformat + from .common import Subscription, SubscriptionState -from my.config import feedbin as config - +from my.config import feedbin as config # isort: skip def inputs() -> Sequence[Path]: return get_files(config.export_path) diff --git a/my/rss/feedly.py b/my/rss/feedly.py index 127ef61..9bf5429 100644 --- a/my/rss/feedly.py +++ b/my/rss/feedly.py @@ -4,9 +4,10 @@ Feedly RSS reader import json from abc import abstractmethod +from collections.abc import Iterator, Sequence from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Protocol, Sequence +from typing import Protocol from my.core import Paths, get_files diff --git a/my/rtm.py b/my/rtm.py index b559ba4..217c969 100644 --- a/my/rtm.py +++ b/my/rtm.py @@ -6,21 +6,19 @@ REQUIRES = [ 'icalendar', ] +import re +from collections.abc import Iterator from datetime import datetime from functools import cached_property -import re -from typing import Dict, List, Iterator -from my.core import make_logger, get_files -from my.core.utils.itertools import make_dict - -from my.config import rtm as config - - -from more_itertools import bucket import icalendar # type: ignore from icalendar.cal import Todo # type: ignore +from more_itertools import bucket +from my.core import get_files, make_logger +from my.core.utils.itertools import make_dict + +from my.config import rtm as config # isort: skip logger = make_logger(__name__) @@ -32,14 +30,14 @@ class MyTodo: self.revision = revision @cached_property - def notes(self) -> List[str]: + def notes(self) -> list[str]: # TODO can there be multiple?? desc = self.todo['DESCRIPTION'] notes = re.findall(r'---\n\n(.*?)\n\nUpdated:', desc, flags=re.DOTALL) return notes @cached_property - def tags(self) -> List[str]: + def tags(self) -> list[str]: desc = self.todo['DESCRIPTION'] [tags_str] = re.findall(r'\nTags: (.*?)\n', desc, flags=re.DOTALL) if tags_str == 'none': @@ -92,11 +90,11 @@ class DAL: for t in self.cal.walk('VTODO'): yield MyTodo(t, self.revision) - def get_todos_by_uid(self) -> Dict[str, MyTodo]: + def get_todos_by_uid(self) -> dict[str, MyTodo]: todos = self.all_todos() return make_dict(todos, key=lambda t: t.uid) - def get_todos_by_title(self) -> Dict[str, List[MyTodo]]: + def get_todos_by_title(self) -> dict[str, list[MyTodo]]: todos = self.all_todos() bucketed = bucket(todos, lambda todo: todo.title) return {k: list(bucketed[k]) for k in bucketed} diff --git a/my/runnerup.py b/my/runnerup.py index a21075a..f5d7d1e 100644 --- a/my/runnerup.py +++ b/my/runnerup.py @@ -6,17 +6,15 @@ REQUIRES = [ 'python-tcxparser', ] +from collections.abc import Iterable from datetime import timedelta from pathlib import Path -from typing import Iterable - -from my.core import Res, get_files, Json -from my.core.compat import fromisoformat import tcxparser # type: ignore[import-untyped] from my.config import runnerup as config - +from my.core import Json, Res, get_files +from my.core.compat import fromisoformat # TODO later, use a proper namedtuple? Workout = Json @@ -70,6 +68,8 @@ def workouts() -> Iterable[Res[Workout]]: from .core.pandas import DataFrameT, check_dataframe, error_to_row + + @check_dataframe def dataframe() -> DataFrameT: def it(): @@ -85,6 +85,8 @@ def dataframe() -> DataFrameT: return df -from .core import stat, Stats +from .core import Stats, stat + + def stats() -> Stats: return stat(dataframe) diff --git a/my/simple.py b/my/simple.py index 7462291..b7f25cd 100644 --- a/my/simple.py +++ b/my/simple.py @@ -1,12 +1,11 @@ ''' Just a demo module for testing and documentation purposes ''' +from collections.abc import Iterator from dataclasses import dataclass -from typing import Iterator - -from my.core import make_config from my.config import simple as user_config +from my.core import make_config @dataclass diff --git a/my/smscalls.py b/my/smscalls.py index 78bf7ee..ccaac72 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -2,6 +2,7 @@ Phone calls and SMS messages Exported using https://play.google.com/store/apps/details?id=com.riteshsahu.SMSBackupRestore&hl=en_US """ +from __future__ import annotations # See: https://www.synctech.com.au/sms-backup-restore/fields-in-xml-backup-files/ for schema @@ -9,8 +10,9 @@ REQUIRES = ['lxml'] from dataclasses import dataclass -from my.core import get_files, stat, Paths, Stats from my.config import smscalls as user_config +from my.core import Paths, Stats, get_files, stat + @dataclass class smscalls(user_config): @@ -18,11 +20,13 @@ class smscalls(user_config): export_path: Paths from my.core.cfg import make_config + config = make_config(smscalls) +from collections.abc import Iterator from datetime import datetime, timezone from pathlib import Path -from typing import NamedTuple, Iterator, Set, Tuple, Optional, Any, Dict, List +from typing import Any, NamedTuple import lxml.etree as etree @@ -33,7 +37,7 @@ class Call(NamedTuple): dt: datetime dt_readable: str duration_s: int - who: Optional[str] + who: str | None # type - 1 = Incoming, 2 = Outgoing, 3 = Missed, 4 = Voicemail, 5 = Rejected, 6 = Refused List. call_type: int @@ -50,7 +54,7 @@ class Call(NamedTuple): # All the field values are read as-is from the underlying database and no conversion is done by the app in most cases. # # The '(Unknown)' is just what my android phone does, not sure if there are others -UNKNOWN: Set[str] = {'(Unknown)'} +UNKNOWN: set[str] = {'(Unknown)'} def _extract_calls(path: Path) -> Iterator[Res[Call]]: @@ -83,7 +87,7 @@ def calls() -> Iterator[Res[Call]]: files = get_files(config.export_path, glob='calls-*.xml') # TODO always replacing with the latter is good, we get better contact names?? - emitted: Set[datetime] = set() + emitted: set[datetime] = set() for p in files: for c in _extract_calls(p): if isinstance(c, Exception): @@ -98,7 +102,7 @@ def calls() -> Iterator[Res[Call]]: class Message(NamedTuple): dt: datetime dt_readable: str - who: Optional[str] + who: str | None message: str phone_number: str # type - 1 = Received, 2 = Sent, 3 = Draft, 4 = Outbox, 5 = Failed, 6 = Queued @@ -112,7 +116,7 @@ class Message(NamedTuple): def messages() -> Iterator[Res[Message]]: files = get_files(config.export_path, glob='sms-*.xml') - emitted: Set[Tuple[datetime, Optional[str], bool]] = set() + emitted: set[tuple[datetime, str | None, bool]] = set() for p in files: for c in _extract_messages(p): if isinstance(c, Exception): @@ -155,20 +159,20 @@ class MMSContentPart(NamedTuple): sequence_index: int content_type: str filename: str - text: Optional[str] - data: Optional[str] + text: str | None + data: str | None class MMS(NamedTuple): dt: datetime dt_readable: str - parts: List[MMSContentPart] + parts: list[MMSContentPart] # NOTE: these is often something like 'Name 1, Name 2', but might be different depending on your client - who: Optional[str] + who: str | None # NOTE: This can be a single phone number, or multiple, split by '~' or ','. Its better to think # of this as a 'key' or 'conversation ID', phone numbers are also present in 'addresses' phone_number: str - addresses: List[Tuple[str, int]] + addresses: list[tuple[str, int]] # 1 = Received, 2 = Sent, 3 = Draft, 4 = Outbox message_type: int @@ -194,7 +198,7 @@ class MMS(NamedTuple): def mms() -> Iterator[Res[MMS]]: files = get_files(config.export_path, glob='sms-*.xml') - emitted: Set[Tuple[datetime, Optional[str], str]] = set() + emitted: set[tuple[datetime, str | None, str]] = set() for p in files: for c in _extract_mms(p): if isinstance(c, Exception): @@ -207,7 +211,7 @@ def mms() -> Iterator[Res[MMS]]: yield c -def _resolve_null_str(value: Optional[str]) -> Optional[str]: +def _resolve_null_str(value: str | None) -> str | None: if value is None: return None # hmm.. theres some risk of the text actually being 'null', but theres @@ -235,7 +239,7 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: yield RuntimeError(f'Missing one or more required attributes [date, readable_date, msg_box, address] in {mxml_str}') continue - addresses: List[Tuple[str, int]] = [] + addresses: list[tuple[str, int]] = [] for addr_parent in mxml.findall('addrs'): for addr in addr_parent.findall('addr'): addr_data = addr.attrib @@ -250,7 +254,7 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: continue addresses.append((user_address, int(user_type))) - content: List[MMSContentPart] = [] + content: list[MMSContentPart] = [] for part_root in mxml.findall('parts'): @@ -267,8 +271,8 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: # # man, attrib is some internal cpython ._Attrib type which can't # be typed by any sort of mappingproxy. maybe a protocol could work..? - part_data: Dict[str, Any] = part.attrib # type: ignore - seq: Optional[str] = part_data.get('seq') + part_data: dict[str, Any] = part.attrib # type: ignore + seq: str | None = part_data.get('seq') if seq == '-1': continue @@ -276,13 +280,13 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: yield RuntimeError(f'seq must be a number, was seq={seq} {type(seq)} in {part_data}') continue - charset_type: Optional[str] = _resolve_null_str(part_data.get('ct')) - filename: Optional[str] = _resolve_null_str(part_data.get('name')) + charset_type: str | None = _resolve_null_str(part_data.get('ct')) + filename: str | None = _resolve_null_str(part_data.get('name')) # in some cases (images, cards), the filename is set in 'cl' instead if filename is None: filename = _resolve_null_str(part_data.get('cl')) - text: Optional[str] = _resolve_null_str(part_data.get('text')) - data: Optional[str] = _resolve_null_str(part_data.get('data')) + text: str | None = _resolve_null_str(part_data.get('text')) + data: str | None = _resolve_null_str(part_data.get('data')) if charset_type is None or filename is None or (text is None and data is None): yield RuntimeError(f'Missing one or more required attributes [ct, name, (text, data)] must be present in {part_data}') diff --git a/my/stackexchange/gdpr.py b/my/stackexchange/gdpr.py index 5292bef..78987be 100644 --- a/my/stackexchange/gdpr.py +++ b/my/stackexchange/gdpr.py @@ -6,8 +6,11 @@ Stackexchange data (uses [[https://stackoverflow.com/legal/gdpr/request][officia ### config from dataclasses import dataclass + from my.config import stackexchange as user_config -from my.core import PathIsh, make_config, get_files, Json +from my.core import Json, PathIsh, get_files, make_config + + @dataclass class stackexchange(user_config): gdpr_path: PathIsh # path to GDPR zip file @@ -17,9 +20,13 @@ config = make_config(stackexchange) # TODO just merge all of them and then filter?.. not sure -from my.core.compat import fromisoformat -from typing import NamedTuple, Iterable +from collections.abc import Iterable from datetime import datetime +from typing import NamedTuple + +from my.core.compat import fromisoformat + + class Vote(NamedTuple): j: Json # todo ip? @@ -62,7 +69,10 @@ class Vote(NamedTuple): # todo expose vote type? import json + from ..core.error import Res + + def votes() -> Iterable[Res[Vote]]: # TODO there is also some site specific stuff in qa/ directory.. not sure if its' more detailed # todo should be defensive? not sure if present when user has no votes @@ -74,6 +84,8 @@ def votes() -> Iterable[Res[Vote]]: yield Vote(r) -from ..core import stat, Stats +from ..core import Stats, stat + + def stats() -> Stats: return stat(votes) diff --git a/my/stackexchange/stexport.py b/my/stackexchange/stexport.py index 812a155..111ed28 100644 --- a/my/stackexchange/stexport.py +++ b/my/stackexchange/stexport.py @@ -16,7 +16,8 @@ from my.core import ( make_config, stat, ) -import my.config + +import my.config # isort: skip @dataclass diff --git a/my/taplog.py b/my/taplog.py index 51eeb72..5e64a72 100644 --- a/my/taplog.py +++ b/my/taplog.py @@ -1,24 +1,26 @@ ''' [[https://play.google.com/store/apps/details?id=com.waterbear.taglog][Taplog]] app data ''' -from datetime import datetime -from typing import NamedTuple, Dict, Optional, Iterable +from __future__ import annotations -from my.core import get_files, stat, Stats -from my.core.sqlite import sqlite_connection +from collections.abc import Iterable +from datetime import datetime +from typing import NamedTuple from my.config import taplog as user_config +from my.core import Stats, get_files, stat +from my.core.sqlite import sqlite_connection class Entry(NamedTuple): - row: Dict + row: dict @property def id(self) -> str: return str(self.row['_id']) @property - def number(self) -> Optional[float]: + def number(self) -> float | None: ns = self.row['number'] # TODO ?? if isinstance(ns, str): diff --git a/my/telegram/telegram_backup.py b/my/telegram/telegram_backup.py index ff4f904..eea7e50 100644 --- a/my/telegram/telegram_backup.py +++ b/my/telegram/telegram_backup.py @@ -1,17 +1,17 @@ """ Telegram data via [fabianonline/telegram_backup](https://github.com/fabianonline/telegram_backup) tool """ +from __future__ import annotations +import sqlite3 +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime, timezone -from struct import unpack_from, calcsize -import sqlite3 -from typing import Dict, Iterator, Optional - -from my.core import datetime_aware, PathIsh -from my.core.sqlite import sqlite_connection +from struct import calcsize, unpack_from from my.config import telegram as user_config +from my.core import PathIsh, datetime_aware +from my.core.sqlite import sqlite_connection @dataclass @@ -23,17 +23,17 @@ class config(user_config.telegram_backup): @dataclass class Chat: id: str - name: Optional[str] + name: str | None # not all users have short handle + groups don't have them either? # TODO hmm some groups have it -- it's just the tool doesn't dump them?? - handle: Optional[str] + handle: str | None # not sure if need type? @dataclass class User: id: str - name: Optional[str] + name: str | None @dataclass @@ -44,7 +44,7 @@ class Message: chat: Chat sender: User text: str - extra_media_info: Optional[str] = None + extra_media_info: str | None = None @property def permalink(self) -> str: @@ -61,7 +61,7 @@ class Message: -Chats = Dict[str, Chat] +Chats = dict[str, Chat] def _message_from_row(r: sqlite3.Row, *, chats: Chats, with_extra_media_info: bool) -> Message: ts = r['time'] # desktop export uses UTC (checked by exporting in winter time vs summer time) @@ -70,7 +70,7 @@ def _message_from_row(r: sqlite3.Row, *, chats: Chats, with_extra_media_info: bo chat = chats[r['source_id']] sender = chats[r['sender_id']] - extra_media_info: Optional[str] = None + extra_media_info: str | None = None if with_extra_media_info and r['has_media'] == 1: # also it's quite hacky, so at least for now it's just an optional attribute behind the flag # defensive because it's a bit tricky to correctly parse without a proper api parser.. @@ -90,7 +90,7 @@ def _message_from_row(r: sqlite3.Row, *, chats: Chats, with_extra_media_info: bo ) -def messages(*, extra_where: Optional[str]=None, with_extra_media_info: bool=False) -> Iterator[Message]: +def messages(*, extra_where: str | None=None, with_extra_media_info: bool=False) -> Iterator[Message]: messages_query = 'SELECT * FROM messages WHERE message_type NOT IN ("service_message", "empty_message")' if extra_where is not None: messages_query += ' AND ' + extra_where @@ -106,7 +106,7 @@ def messages(*, extra_where: Optional[str]=None, with_extra_media_info: bool=Fal for r in db.execute('SELECT * FROM users ORDER BY id'): first = r["first_name"] last = r["last_name"] - name: Optional[str] + name: str | None if first is not None and last is not None: name = f'{first} {last}' else: @@ -121,7 +121,7 @@ def messages(*, extra_where: Optional[str]=None, with_extra_media_info: bool=Fal yield _message_from_row(r, chats=chats, with_extra_media_info=with_extra_media_info) -def _extract_extra_media_info(data: bytes) -> Optional[str]: +def _extract_extra_media_info(data: bytes) -> str | None: # ugh... very hacky, but it does manage to extract from 90% of messages that have media pos = 0 diff --git a/my/tests/bluemaestro.py b/my/tests/bluemaestro.py index 2d7c81e..d139a8f 100644 --- a/my/tests/bluemaestro.py +++ b/my/tests/bluemaestro.py @@ -1,4 +1,4 @@ -from typing import Iterator +from collections.abc import Iterator import pytest from more_itertools import one diff --git a/my/tests/body/weight.py b/my/tests/body/weight.py index 069e940..f26ccf2 100644 --- a/my/tests/body/weight.py +++ b/my/tests/body/weight.py @@ -1,8 +1,10 @@ from pathlib import Path -import pytz -from my.core.cfg import tmp_config + import pytest +import pytz + from my.body.weight import from_orgmode +from my.core.cfg import tmp_config def test_body_weight() -> None: diff --git a/my/tests/commits.py b/my/tests/commits.py index c967027..48e349f 100644 --- a/my/tests/commits.py +++ b/my/tests/commits.py @@ -1,14 +1,11 @@ import os from pathlib import Path -from more_itertools import bucket import pytest - - -from my.core.cfg import tmp_config +from more_itertools import bucket from my.coding.commits import commits - +from my.core.cfg import tmp_config pytestmark = pytest.mark.skipif( os.name == 'nt', diff --git a/my/tests/location/fallback.py b/my/tests/location/fallback.py index 10a4e5b..c09b902 100644 --- a/my/tests/location/fallback.py +++ b/my/tests/location/fallback.py @@ -2,8 +2,8 @@ To test my.location.fallback_location.all """ +from collections.abc import Iterator from datetime import datetime, timedelta, timezone -from typing import Iterator import pytest from more_itertools import ilen diff --git a/my/tests/reddit.py b/my/tests/reddit.py index 4f1ec51..4ddccf8 100644 --- a/my/tests/reddit.py +++ b/my/tests/reddit.py @@ -1,16 +1,14 @@ import pytest from more_itertools import consume -from my.core.cfg import tmp_config -from my.core.utils.itertools import ensure_unique - -from .common import testdata - - # deliberately use mixed style imports on the top level and inside the methods to test tmp_config stuff # todo won't really be necessary once we migrate to lazy user config import my.reddit.all as my_reddit_all import my.reddit.rexport as my_reddit_rexport +from my.core.cfg import tmp_config +from my.core.utils.itertools import ensure_unique + +from .common import testdata def test_basic_1() -> None: diff --git a/my/time/tz/common.py b/my/time/tz/common.py index 13c8ac0..c0dd262 100644 --- a/my/time/tz/common.py +++ b/my/time/tz/common.py @@ -3,7 +3,6 @@ from typing import Callable, Literal, cast from my.core import datetime_aware - ''' Depending on the specific data provider and your level of paranoia you might expect different behaviour.. E.g.: - if your objects already have tz info, you might not need to call localize() at all diff --git a/my/time/tz/main.py b/my/time/tz/main.py index fafc5fe..bdd36b1 100644 --- a/my/time/tz/main.py +++ b/my/time/tz/main.py @@ -6,6 +6,7 @@ from datetime import datetime from my.core import datetime_aware + # todo hmm, kwargs isn't mypy friendly.. but specifying types would require duplicating default args. uhoh def localize(dt: datetime, **kwargs) -> datetime_aware: # todo document patterns for combining multiple data sources diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 4920333..58b5bf7 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -2,6 +2,8 @@ Timezone data provider, guesses timezone based on location data (e.g. GPS) ''' +from __future__ import annotations + REQUIRES = [ # for determining timezone by coordinate 'timezonefinder', @@ -10,6 +12,7 @@ REQUIRES = [ import heapq import os from collections import Counter +from collections.abc import Iterable, Iterator from dataclasses import dataclass from datetime import date, datetime from functools import lru_cache @@ -17,14 +20,7 @@ from itertools import groupby from typing import ( TYPE_CHECKING, Any, - Dict, - Iterable, - Iterator, - List, - Optional, Protocol, - Set, - Tuple, ) import pytz @@ -102,7 +98,7 @@ def _timezone_finder(*, fast: bool) -> Any: # for backwards compatibility -def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: +def _locations() -> Iterator[tuple[LatLon, datetime_aware]]: try: import my.location.all @@ -125,7 +121,7 @@ def _locations() -> Iterator[Tuple[LatLon, datetime_aware]]: # TODO: could use heapmerge or sort the underlying iterators somehow? # see https://github.com/karlicoss/HPI/pull/237#discussion_r858372934 -def _sorted_locations() -> List[Tuple[LatLon, datetime_aware]]: +def _sorted_locations() -> list[tuple[LatLon, datetime_aware]]: return sorted(_locations(), key=lambda x: x[1]) @@ -140,7 +136,7 @@ class DayWithZone: zone: Zone -def _find_tz_for_locs(finder: Any, locs: Iterable[Tuple[LatLon, datetime]]) -> Iterator[DayWithZone]: +def _find_tz_for_locs(finder: Any, locs: Iterable[tuple[LatLon, datetime]]) -> Iterator[DayWithZone]: for (lat, lon), dt in locs: # TODO right. its _very_ slow... zone = finder.timezone_at(lat=lat, lng=lon) @@ -172,7 +168,7 @@ def _iter_local_dates() -> Iterator[DayWithZone]: # TODO: warnings doesn't actually warn? # warnings = [] - locs: Iterable[Tuple[LatLon, datetime]] + locs: Iterable[tuple[LatLon, datetime]] locs = _sorted_locations() if cfg.sort_locations else _locations() yield from _find_tz_for_locs(finder, locs) @@ -187,7 +183,7 @@ def _iter_local_dates_fallback() -> Iterator[DayWithZone]: cfg = make_config() - def _fallback_locations() -> Iterator[Tuple[LatLon, datetime]]: + def _fallback_locations() -> Iterator[tuple[LatLon, datetime]]: for loc in sorted(flocs(), key=lambda x: x.dt): yield ((loc.lat, loc.lon), loc.dt) @@ -225,14 +221,14 @@ def _iter_tzs() -> Iterator[DayWithZone]: # we need to sort them first before we can do a groupby by_day = lambda p: p.day - local_dates: List[DayWithZone] = sorted(_iter_local_dates(), key=by_day) + local_dates: list[DayWithZone] = sorted(_iter_local_dates(), key=by_day) logger.debug(f"no. of items using exact locations: {len(local_dates)}") - local_dates_fallback: List[DayWithZone] = sorted(_iter_local_dates_fallback(), key=by_day) + local_dates_fallback: list[DayWithZone] = sorted(_iter_local_dates_fallback(), key=by_day) # find days that are in fallback but not in local_dates (i.e., missing days) - local_dates_set: Set[date] = {d.day for d in local_dates} - use_fallback_days: List[DayWithZone] = [d for d in local_dates_fallback if d.day not in local_dates_set] + local_dates_set: set[date] = {d.day for d in local_dates} + use_fallback_days: list[DayWithZone] = [d for d in local_dates_fallback if d.day not in local_dates_set] logger.debug(f"no. of items being used from fallback locations: {len(use_fallback_days)}") # combine local_dates and missing days from fallback into a sorted list @@ -246,20 +242,20 @@ def _iter_tzs() -> Iterator[DayWithZone]: @lru_cache(1) -def _day2zone() -> Dict[date, pytz.BaseTzInfo]: +def _day2zone() -> dict[date, pytz.BaseTzInfo]: # NOTE: kinda unfortunate that this will have to process all days before returning result for just one # however otherwise cachew cache might never be initialized properly # so we'll always end up recomputing everyting during subsequent runs return {dz.day: pytz.timezone(dz.zone) for dz in _iter_tzs()} -def _get_day_tz(d: date) -> Optional[pytz.BaseTzInfo]: +def _get_day_tz(d: date) -> pytz.BaseTzInfo | None: return _day2zone().get(d) # ok to cache, there are only a few home locations? @lru_cache(None) -def _get_home_tz(loc: LatLon) -> Optional[pytz.BaseTzInfo]: +def _get_home_tz(loc: LatLon) -> pytz.BaseTzInfo | None: (lat, lng) = loc finder = _timezone_finder(fast=False) # ok to use slow here for better precision zone = finder.timezone_at(lat=lat, lng=lng) @@ -270,7 +266,7 @@ def _get_home_tz(loc: LatLon) -> Optional[pytz.BaseTzInfo]: return pytz.timezone(zone) -def get_tz(dt: datetime) -> Optional[pytz.BaseTzInfo]: +def get_tz(dt: datetime) -> pytz.BaseTzInfo | None: ''' Given a datetime, returns the timezone for that date. ''' diff --git a/my/tinder/android.py b/my/tinder/android.py index d9b256b..a09794f 100644 --- a/my/tinder/android.py +++ b/my/tinder/android.py @@ -3,20 +3,22 @@ Tinder data from Android app database (in =/data/data/com.tinder/databases/tinde """ from __future__ import annotations -from collections import defaultdict, Counter +import sqlite3 +from collections import Counter, defaultdict +from collections.abc import Iterator, Mapping, Sequence from dataclasses import dataclass from datetime import datetime, timezone from itertools import chain from pathlib import Path -import sqlite3 -from typing import Sequence, Iterator, Union, Dict, List, Mapping +from typing import Union -from my.core import Paths, get_files, Res, stat, Stats, datetime_aware, make_logger +from my.core import Paths, Res, Stats, datetime_aware, get_files, make_logger, stat from my.core.common import unique_everseen from my.core.compat import assert_never from my.core.error import echain from my.core.sqlite import sqlite_connection -import my.config + +import my.config # isort: skip logger = make_logger(__name__) @@ -164,8 +166,8 @@ def _parse_msg(row: sqlite3.Row) -> _Message: # todo maybe it's rich_entities method? def entities() -> Iterator[Res[Entity]]: - id2person: Dict[str, Person] = {} - id2match: Dict[str, Match] = {} + id2person: dict[str, Person] = {} + id2match: dict[str, Match] = {} for x in unique_everseen(_entities): if isinstance(x, Exception): yield x @@ -217,7 +219,7 @@ def messages() -> Iterator[Res[Message]]: # todo not sure, maybe it's not fundamental enough to keep here... def match2messages() -> Iterator[Res[Mapping[Match, Sequence[Message]]]]: - res: Dict[Match, List[Message]] = defaultdict(list) + res: dict[Match, list[Message]] = defaultdict(list) for x in entities(): if isinstance(x, Exception): yield x diff --git a/my/topcoder.py b/my/topcoder.py index 07f71be..56403e2 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -1,14 +1,14 @@ +import json +from collections.abc import Iterator, Sequence from dataclasses import dataclass from functools import cached_property -import json from pathlib import Path -from typing import Iterator, Sequence -from my.core import get_files, Res, datetime_aware +from my.core import Res, datetime_aware, get_files from my.core.compat import fromisoformat from my.experimental.destructive_parsing import Manager -from my.config import topcoder as config # type: ignore[attr-defined] +from my.config import topcoder as config # type: ignore[attr-defined] # isort: skip def inputs() -> Sequence[Path]: diff --git a/my/twitter/all.py b/my/twitter/all.py index 4714021..c2c471e 100644 --- a/my/twitter/all.py +++ b/my/twitter/all.py @@ -1,11 +1,11 @@ """ Unified Twitter data (merged from the archive and periodic updates) """ -from typing import Iterator +from collections.abc import Iterator + from ..core import Res from ..core.source import import_source -from .common import merge_tweets, Tweet - +from .common import Tweet, merge_tweets # NOTE: you can comment out the sources you don't need src_twint = import_source(module_name='my.twitter.twint') diff --git a/my/twitter/android.py b/my/twitter/android.py index ada04ae..88c9389 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -4,21 +4,21 @@ Twitter data from official app for Android from __future__ import annotations +import re +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -import re from struct import unpack_from -from typing import Iterator, Sequence, Set -from my.core import datetime_aware, get_files, LazyLogger, Paths, Res +from my.core import LazyLogger, Paths, Res, datetime_aware, get_files from my.core.common import unique_everseen from my.core.sqlite import sqlite_connect_immutable -import my.config - from .common import permalink +import my.config # isort: skip + logger = LazyLogger(__name__) @@ -155,7 +155,7 @@ _SELECT_OWN_TWEETS = '_SELECT_OWN_TWEETS' def get_own_user_id(conn) -> str: # unclear what's the reliable way to query it, so we use multiple different ones and arbitrate # NOTE: 'SELECT DISTINCT ev_owner_id FROM lists' doesn't work, might include lists from other people? - res: Set[str] = set() + res: set[str] = set() # need to cast as it's int by default for q in [ 'SELECT DISTINCT CAST(list_mapping_user_id AS TEXT) FROM list_mapping', @@ -239,7 +239,7 @@ def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: NOT (statuses.in_r_user_id == -1 AND statuses.in_r_status_id == -1 AND statuses.conversation_id == 0) ''' - def _query_one(*, where: str, quoted: Set[int]) -> Iterator[Res[Tweet]]: + def _query_one(*, where: str, quoted: set[int]) -> Iterator[Res[Tweet]]: for ( tweet_id, user_username, @@ -263,7 +263,7 @@ def _process_one(f: Path, *, where: str) -> Iterator[Res[Tweet]]: text=content, ) - quoted: Set[int] = set() + quoted: set[int] = set() yield from _query_one(where=db_where, quoted=quoted) # get quoted tweets 'recursively' # TODO maybe do it for favs/bookmarks too? not sure diff --git a/my/twitter/archive.py b/my/twitter/archive.py index 1573754..c9d2dbc 100644 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -7,6 +7,7 @@ from __future__ import annotations import html import json # hmm interesting enough, orjson didn't give much speedup here? from abc import abstractmethod +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime from functools import cached_property @@ -14,8 +15,6 @@ from itertools import chain from pathlib import Path from typing import ( TYPE_CHECKING, - Iterator, - Sequence, ) from more_itertools import unique_everseen diff --git a/my/twitter/common.py b/my/twitter/common.py index 258216f..8c346f6 100644 --- a/my/twitter/common.py +++ b/my/twitter/common.py @@ -1,17 +1,19 @@ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip +from collections.abc import Iterator from itertools import chain -from typing import Iterator, Any +from typing import Any from more_itertools import unique_everseen - # TODO add proper Protocol for Tweet Tweet = Any TweetId = str -from my.core import warn_if_empty, Res +from my.core import Res, warn_if_empty + + @warn_if_empty def merge_tweets(*sources: Iterator[Res[Tweet]]) -> Iterator[Res[Tweet]]: def key(r: Res[Tweet]): diff --git a/my/twitter/talon.py b/my/twitter/talon.py index 1b79727..dbf2e2e 100644 --- a/my/twitter/talon.py +++ b/my/twitter/talon.py @@ -7,10 +7,11 @@ from __future__ import annotations import re import sqlite3 from abc import abstractmethod +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Iterator, Sequence, Union +from typing import Union from my.core import Paths, Res, datetime_aware, get_files from my.core.common import unique_everseen diff --git a/my/twitter/twint.py b/my/twitter/twint.py index ceb5406..5106923 100644 --- a/my/twitter/twint.py +++ b/my/twitter/twint.py @@ -1,17 +1,17 @@ """ Twitter data (tweets and favorites). Uses [[https://github.com/twintproject/twint][Twint]] data export. """ +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import NamedTuple, Iterator, List +from typing import NamedTuple - -from my.core import Paths, Res, get_files, LazyLogger, Json, datetime_aware, stat, Stats +from my.core import Json, LazyLogger, Paths, Res, Stats, datetime_aware, get_files, stat from my.core.cfg import make_config from my.core.sqlite import sqlite_connection -from my.config import twint as user_config +from my.config import twint as user_config # isort: skip # TODO move to twitter.twint config structure @@ -76,7 +76,7 @@ class Tweet(NamedTuple): return text @property - def urls(self) -> List[str]: + def urls(self) -> list[str]: ustr = self.row['urls'] if len(ustr) == 0: return [] diff --git a/my/util/hpi_heartbeat.py b/my/util/hpi_heartbeat.py index 84790a4..6dcac7e 100644 --- a/my/util/hpi_heartbeat.py +++ b/my/util/hpi_heartbeat.py @@ -5,12 +5,13 @@ In particular the behaviour of import_original_module function The idea of testing is that overlays extend this module, and add their own items to items(), and the checker asserts all overlays have contributed. """ -from my.core import __NOT_HPI_MODULE__ +from my.core import __NOT_HPI_MODULE__ # isort: skip + +import sys +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime -import sys -from typing import Iterator, List NOW = datetime.now() @@ -19,10 +20,10 @@ NOW = datetime.now() class Item: dt: datetime message: str - path: List[str] + path: list[str] -def get_pkg_path() -> List[str]: +def get_pkg_path() -> list[str]: pkg = sys.modules[__package__] return list(pkg.__path__) diff --git a/my/vk/favorites.py b/my/vk/favorites.py index 9caae6d..5f278ff 100644 --- a/my/vk/favorites.py +++ b/my/vk/favorites.py @@ -1,20 +1,21 @@ # todo: uses my private export script?, timezone +from __future__ import annotations + +import json +from collections.abc import Iterable, Iterator from dataclasses import dataclass from datetime import datetime, timezone -import json -from typing import Iterator, Iterable, Optional - -from my.core import Json, datetime_aware, stat, Stats -from my.core.error import Res from my.config import vk as config # type: ignore[attr-defined] +from my.core import Json, Stats, datetime_aware, stat +from my.core.error import Res @dataclass class Favorite: dt: datetime_aware title: str - url: Optional[str] + url: str | None text: str diff --git a/my/vk/vk_messages_backup.py b/my/vk/vk_messages_backup.py index c73587f..4f593c8 100644 --- a/my/vk/vk_messages_backup.py +++ b/my/vk/vk_messages_backup.py @@ -2,18 +2,16 @@ VK data (exported by [[https://github.com/Totktonada/vk_messages_backup][Totktonada/vk_messages_backup]]) ''' # note: could reuse the original repo, but little point I guess since VK closed their API +import json +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime -import json -from typing import Dict, Iterator import pytz -from my.core import stat, Stats, Json, Res, datetime_aware, get_files -from my.core.common import unique_everseen - from my.config import vk_messages_backup as config - +from my.core import Json, Res, Stats, datetime_aware, get_files, stat +from my.core.common import unique_everseen # I think vk_messages_backup used this tz? # not sure if vk actually used to return this tz in api? @@ -45,7 +43,7 @@ class Message: body: str -Users = Dict[Uid, User] +Users = dict[Uid, User] def users() -> Users: diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 3dfed3e..27ee743 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -3,18 +3,19 @@ Whatsapp data from Android app database (in =/data/data/com.whatsapp/databases/m """ from __future__ import annotations +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -import sqlite3 -from typing import Union, Sequence, Iterator, Optional +from typing import Union -from my.core import get_files, Paths, datetime_aware, Res, make_logger, make_config +from my.core import Paths, Res, datetime_aware, get_files, make_config, make_logger from my.core.common import unique_everseen from my.core.error import echain, notnone from my.core.sqlite import sqlite_connection -import my.config +import my.config # isort: skip logger = make_logger(__name__) @@ -23,7 +24,7 @@ logger = make_logger(__name__) class Config(my.config.whatsapp.android): # paths[s]/glob to the exported sqlite databases export_path: Paths - my_user_id: Optional[str] = None + my_user_id: str | None = None config = make_config(Config) @@ -38,13 +39,13 @@ class Chat: id: str # todo not sure how to support renames? # could change Chat object itself, but this won't work well with incremental processing.. - name: Optional[str] + name: str | None @dataclass(unsafe_hash=True) class Sender: id: str - name: Optional[str] + name: str | None @dataclass(unsafe_hash=True) @@ -53,7 +54,7 @@ class Message: id: str dt: datetime_aware sender: Sender - text: Optional[str] + text: str | None Entity = Union[Chat, Sender, Message] @@ -125,9 +126,9 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: ts: int = notnone(r['timestamp']) dt = datetime.fromtimestamp(ts / 1000, tz=timezone.utc) - text: Optional[str] = r['text_data'] - media_file_path: Optional[str] = r['file_path'] - media_file_size: Optional[int] = r['file_size'] + text: str | None = r['text_data'] + media_file_path: str | None = r['file_path'] + media_file_size: int | None = r['file_size'] message_type = r['message_type'] diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index f29b2e3..703715f 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -1,7 +1,8 @@ from __future__ import annotations +from collections.abc import Iterable, Iterator from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Iterable, Iterator +from typing import TYPE_CHECKING, Any from my.core import Res, Stats, datetime_aware, make_logger, stat, warnings from my.core.compat import deprecated diff --git a/my/zotero.py b/my/zotero.py index 4440aae..8eb34ba 100644 --- a/my/zotero.py +++ b/my/zotero.py @@ -1,14 +1,16 @@ +from __future__ import annotations as _annotations + +import json +import sqlite3 +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone -import json -from typing import Iterator, Optional, Dict, Any, Sequence from pathlib import Path -import sqlite3 +from typing import Any -from my.core import make_logger, Res, datetime_aware +from my.core import Res, datetime_aware, make_logger from my.core.sqlite import sqlite_copy_and_open - logger = make_logger(__name__) @@ -26,7 +28,7 @@ class Item: """Corresponds to 'Zotero item'""" file: Path title: str - url: Optional[Url] + url: Url | None tags: Sequence[str] @@ -39,8 +41,8 @@ class Annotation: page: int """0-indexed""" - text: Optional[str] - comment: Optional[str] + text: str | None + comment: str | None tags: Sequence[str] color_hex: str """Original hex-encoded color in zotero""" @@ -97,7 +99,7 @@ WHERE ID.fieldID = 13 AND IA.itemID = ? # TODO maybe exclude 'private' methods from detection? -def _query_raw() -> Iterator[Res[Dict[str, Any]]]: +def _query_raw() -> Iterator[Res[dict[str, Any]]]: [db] = inputs() with sqlite_copy_and_open(db) as conn: @@ -157,7 +159,7 @@ def _hex2human(color_hex: str) -> str: }.get(color_hex, color_hex) -def _parse_annotation(r: Dict) -> Annotation: +def _parse_annotation(r: dict) -> Annotation: text = r['text'] comment = r['comment'] # todo use json query for this? diff --git a/my/zulip/organization.py b/my/zulip/organization.py index 2e0df4b..d0cfcb7 100644 --- a/my/zulip/organization.py +++ b/my/zulip/organization.py @@ -6,11 +6,11 @@ from __future__ import annotations import json from abc import abstractmethod +from collections.abc import Iterator, Sequence from dataclasses import dataclass from datetime import datetime, timezone from itertools import count from pathlib import Path -from typing import Iterator, Sequence from my.core import ( Json, diff --git a/ruff.toml b/ruff.toml index 5fbd657..3d803e7 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,4 +1,4 @@ -target-version = "py38" # NOTE: inferred from pyproject.toml if present +target-version = "py39" # NOTE: inferred from pyproject.toml if present lint.extend-select = [ "F", # flakes rules -- default, but extend just in case @@ -26,8 +26,8 @@ lint.extend-select = [ "TID", # various imports suggestions "TRY", # various exception handling rules "UP", # detect deprecated python stdlib stuff - # "FA", # suggest using from __future__ import annotations TODO enable later after we make sure cachew works? - # "PTH", # pathlib migration -- TODO enable later + "FA", # suggest using from __future__ import annotations + "PTH", # pathlib migration "ARG", # unused argument checks # "A", # builtin shadowing -- TODO handle later # "EM", # TODO hmm could be helpful to prevent duplicate err msg in traceback.. but kinda annoying @@ -35,6 +35,11 @@ lint.extend-select = [ # "ALL", # uncomment this to check for new rules! ] +# Preserve types, even if a file imports `from __future__ import annotations` +# we need this for cachew to work with HPI types on 3.9 +# can probably remove after 3.10? +lint.pyupgrade.keep-runtime-typing = true + lint.ignore = [ "D", # annoying nags about docstrings "N", # pep naming @@ -68,11 +73,6 @@ lint.ignore = [ "F841", # Local variable `count` is assigned to but never used ### -### TODO should be fine to use these with from __future__ import annotations? -### there was some issue with cachew though... double check this? - "UP006", # use type instead of Type - "UP007", # use X | Y instead of Union -### "RUF100", # unused noqa -- handle later "RUF012", # mutable class attrs should be annotated with ClassVar... ugh pretty annoying for user configs From a2b397ec4a83e6fded7c758470c49f6f18f2ab81 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Tue, 22 Oct 2024 20:50:37 +0100 Subject: [PATCH 47/55] my.whatsapp.android: adapt to new db format --- my/books/kobo.py | 2 +- my/whatsapp/android.py | 33 ++++++++++++++++++++++++++------- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/my/books/kobo.py b/my/books/kobo.py index 899ef31..40b7ed7 100644 --- a/my/books/kobo.py +++ b/my/books/kobo.py @@ -3,4 +3,4 @@ from my.core import warnings warnings.high('my.books.kobo is deprecated! Please use my.kobo instead!') from my.core.util import __NOT_HPI_MODULE__ -from my.kobo import * # type: ignore[no-redef] +from my.kobo import * diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 27ee743..3cd4436 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -1,6 +1,7 @@ """ Whatsapp data from Android app database (in =/data/data/com.whatsapp/databases/msgstore.db=) """ + from __future__ import annotations import sqlite3 @@ -63,11 +64,27 @@ Entity = Union[Chat, Sender, Message] def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: # TODO later, split out Chat/Sender objects separately to safe on object creation, similar to other android data sources + try: + db.execute('SELECT jid_row_id FROM chat_view') + except sqlite3.OperationalError as oe: + if 'jid_row_id' not in str(oe): + raise oe + new_version_202410 = False + else: + new_version_202410 = True + + if new_version_202410: + chat_id_col = 'jid.raw_string' + jid_join = 'JOIN jid ON jid._id == chat_view.jid_row_id' + else: + chat_id_col = 'chat_view.raw_string_jid' + jid_join = '' + chats = {} for r in db.execute( - ''' - SELECT raw_string_jid AS chat_id, subject - FROM chat_view + f''' + SELECT {chat_id_col} AS chat_id, subject + FROM chat_view {jid_join} WHERE chat_id IS NOT NULL /* seems that it might be null for chats that are 'recycled' (the db is more like an LRU cache) */ ''' ): @@ -89,6 +106,7 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: ): # TODO seems that msgstore.db doesn't have contact names # perhaps should extract from wa.db and match against wa_contacts.jid? + # TODO these can also be chats? not sure if need to include... s = Sender( id=r['raw_string'], name=None, @@ -100,9 +118,9 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: # so even if it seems as if it has a column (e.g. for attachment path), there is actually no such data # so makes more sense to just query message column directly for r in db.execute( - ''' + f''' SELECT - C.raw_string_jid AS chat_id, + {chat_id_col} AS chat_id, M.key_id, M.timestamp, sender_jid_row_id, M.from_me, @@ -111,8 +129,9 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: MM.file_size, M.message_type FROM message AS M - LEFT JOIN chat_view AS C ON M.chat_row_id = C._id - LEFT JOIN message_media AS MM ON M._id = MM.message_row_id + LEFT JOIN chat_view ON M.chat_row_id = chat_view._id + {jid_join} + left JOIN message_media AS MM ON M._id = MM.message_row_id WHERE M.key_id != -1 /* key_id -1 is some sort of fake message where everything is null */ /* type 7 seems to be some dummy system message. sometimes contain chat name, but usually null, so ignore them From 7ab6f0d5cbce2241ba8a7848ff1bf18e147d26cf Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Fri, 25 Oct 2024 09:39:00 -0700 Subject: [PATCH 48/55] chore: update urls --- README.org | 4 ++-- doc/DENYLIST.md | 6 +++--- doc/MODULES.org | 12 ++++++------ doc/MODULE_DESIGN.org | 8 ++++---- doc/OVERLAYS.org | 2 +- doc/QUERY.md | 6 +++--- doc/SETUP.org | 2 +- misc/.flake8-karlicoss | 2 +- my/browser/active_browser.py | 2 +- my/browser/export.py | 2 +- my/google/takeout/parser.py | 10 +++++----- my/ip/all.py | 4 ++-- my/ip/common.py | 2 +- my/location/fallback/via_ip.py | 2 +- my/location/google_takeout.py | 2 +- my/location/google_takeout_semantic.py | 2 +- my/location/via_ip.py | 2 +- my/reddit/pushshift.py | 6 +++--- 18 files changed, 38 insertions(+), 38 deletions(-) diff --git a/README.org b/README.org index c065a0c..79621a5 100644 --- a/README.org +++ b/README.org @@ -723,10 +723,10 @@ If you want to write modules for personal use but don't want to merge them into Other HPI Repositories: -- [[https://github.com/seanbreckenridge/HPI][seanbreckenridge/HPI]] +- [[https://github.com/purarue/HPI][purarue/HPI]] - [[https://github.com/madelinecameron/hpi][madelinecameron/HPI]] -If you want to create your own to create your own modules/override something here, you can use the [[https://github.com/seanbreckenridge/HPI-template][template]]. +If you want to create your own to create your own modules/override something here, you can use the [[https://github.com/purarue/HPI-template][template]]. * Related links :PROPERTIES: diff --git a/doc/DENYLIST.md b/doc/DENYLIST.md index 440715c..3d8dea0 100644 --- a/doc/DENYLIST.md +++ b/doc/DENYLIST.md @@ -76,7 +76,7 @@ This would typically be used in an overridden `all.py` file, or in a one-off scr which you may want to filter out some items from a source, progressively adding more items to the denylist as you go. -A potential `my/ip/all.py` file might look like (Sidenote: `discord` module from [here](https://github.com/seanbreckenridge/HPI)): +A potential `my/ip/all.py` file might look like (Sidenote: `discord` module from [here](https://github.com/purarue/HPI)): ```python from typing import Iterator @@ -119,9 +119,9 @@ python3 -c 'from my.ip import all; all.deny.deny_cli(all.ips())' To edit the `all.py`, you could either: - install it as editable (`python3 -m pip install --user -e ./HPI`), and then edit the file directly -- or, create a namespace package, which splits the package across multiple directories. For info on that see [`MODULE_DESIGN`](https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#namespace-packages), [`reorder_editable`](https://github.com/seanbreckenridge/reorder_editable), and possibly the [`HPI-template`](https://github.com/seanbreckenridge/HPI-template) to create your own HPI namespace package to create your own `all.py` file. +- or, create a namespace package, which splits the package across multiple directories. For info on that see [`MODULE_DESIGN`](https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#namespace-packages), [`reorder_editable`](https://github.com/purarue/reorder_editable), and possibly the [`HPI-template`](https://github.com/purarue/HPI-template) to create your own HPI namespace package to create your own `all.py` file. -For a real example of this see, [seanbreckenridge/HPI-personal](https://github.com/seanbreckenridge/HPI-personal/blob/master/my/ip/all.py) +For a real example of this see, [purarue/HPI-personal](https://github.com/purarue/HPI-personal/blob/master/my/ip/all.py) Sidenote: the reason why we want to specifically override the all.py and not just create a script that filters out the items you're diff --git a/doc/MODULES.org b/doc/MODULES.org index 9f48024..347d88d 100644 --- a/doc/MODULES.org +++ b/doc/MODULES.org @@ -76,7 +76,7 @@ The config snippets below are meant to be modified accordingly and *pasted into You don't have to set up all modules at once, it's recommended to do it gradually, to get the feel of how HPI works. -For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py][config]] +For an extensive/complex example, you can check out ~@purarue~'s [[https://github.com/purarue/dotfiles/blob/master/.config/my/my/config/__init__.py][config]] # Nested Configurations before the doc generation using the block below ** [[file:../my/reddit][my.reddit]] @@ -96,7 +96,7 @@ For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[http class pushshift: ''' - Uses [[https://github.com/seanbreckenridge/pushshift_comment_export][pushshift]] to get access to old comments + Uses [[https://github.com/purarue/pushshift_comment_export][pushshift]] to get access to old comments ''' # path[s]/glob to the exported JSON data @@ -106,7 +106,7 @@ For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[http ** [[file:../my/browser/][my.browser]] - Parses browser history using [[http://github.com/seanbreckenridge/browserexport][browserexport]] + Parses browser history using [[http://github.com/purarue/browserexport][browserexport]] #+begin_src python class browser: @@ -132,7 +132,7 @@ For an extensive/complex example, you can check out ~@seanbreckenridge~'s [[http You might also be able to use [[file:../my/location/via_ip.py][my.location.via_ip]] which uses =my.ip.all= to provide geolocation data for an IPs (though no IPs are provided from any - of the sources here). For an example of usage, see [[https://github.com/seanbreckenridge/HPI/tree/master/my/ip][here]] + of the sources here). For an example of usage, see [[https://github.com/purarue/HPI/tree/master/my/ip][here]] #+begin_src python class location: @@ -256,9 +256,9 @@ for cls, p in modules: ** [[file:../my/google/takeout/parser.py][my.google.takeout.parser]] - Parses Google Takeout using [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] + Parses Google Takeout using [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] - See [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] for more information about how to export and organize your takeouts + See [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] for more information about how to export and organize your takeouts If the =DISABLE_TAKEOUT_CACHE= environment variable is set, this won't cache individual exports in =~/.cache/google_takeout_parser= diff --git a/doc/MODULE_DESIGN.org b/doc/MODULE_DESIGN.org index 7aedf2f..442dbf2 100644 --- a/doc/MODULE_DESIGN.org +++ b/doc/MODULE_DESIGN.org @@ -67,7 +67,7 @@ If you want to disable a source, you have a few options. ... that suppresses the warning message and lets you use ~my.location.all~ without having to change any lines of code -Another benefit is that all the custom sources/data is localized to the ~all.py~ file, so a user can override the ~all.py~ (see the sections below on ~namespace packages~) file in their own HPI repository, adding additional sources without having to maintain a fork and patching in changes as things eventually change. For a 'real world' example of that, see [[https://github.com/seanbreckenridge/HPI#partially-in-usewith-overrides][seanbreckenridge]]s location and ip modules. +Another benefit is that all the custom sources/data is localized to the ~all.py~ file, so a user can override the ~all.py~ (see the sections below on ~namespace packages~) file in their own HPI repository, adding additional sources without having to maintain a fork and patching in changes as things eventually change. For a 'real world' example of that, see [[https://github.com/purarue/HPI#partially-in-usewith-overrides][purarue]]s location and ip modules. This is of course not required for personal or single file modules, its just the pattern that seems to have the least amount of friction for the user, while being extendable, and without using a bulky plugin system to let users add additional sources. @@ -208,13 +208,13 @@ Where ~lastfm.py~ is your version of ~my.lastfm~, which you've copied from this Then, running ~python3 -m pip install -e .~ in that directory would install that as part of the namespace package, and assuming (see below for possible issues) this appears on ~sys.path~ before the upstream repository, your ~lastfm.py~ file overrides the upstream. Adding more files, like ~my.some_new_module~ into that directory immediately updates the global ~my~ package -- allowing you to quickly add new modules without having to re-install. -If you install both directories as editable packages (which has the benefit of any changes you making in either repository immediately updating the globally installed ~my~ package), there are some concerns with which editable install appears on your ~sys.path~ first. If you wanted your modules to override the upstream modules, yours would have to appear on the ~sys.path~ first (this is the same reason that =custom_lastfm_overlay= must be at the front of your ~PYTHONPATH~). For more details and examples on dealing with editable namespace packages in the context of HPI, see the [[https://github.com/seanbreckenridge/reorder_editable][reorder_editable]] repository. +If you install both directories as editable packages (which has the benefit of any changes you making in either repository immediately updating the globally installed ~my~ package), there are some concerns with which editable install appears on your ~sys.path~ first. If you wanted your modules to override the upstream modules, yours would have to appear on the ~sys.path~ first (this is the same reason that =custom_lastfm_overlay= must be at the front of your ~PYTHONPATH~). For more details and examples on dealing with editable namespace packages in the context of HPI, see the [[https://github.com/purarue/reorder_editable][reorder_editable]] repository. There is no limit to how many directories you could install into a single namespace package, which could be a possible way for people to install additional HPI modules, without worrying about the module count here becoming too large to manage. -There are some other users [[https://github.com/hpi/hpi][who have begun publishing their own modules]] as namespace packages, which you could potentially install and use, in addition to this repository, if any of those interest you. If you want to create your own you can use the [[https://github.com/seanbreckenridge/HPI-template][template]] to get started. +There are some other users [[https://github.com/hpi/hpi][who have begun publishing their own modules]] as namespace packages, which you could potentially install and use, in addition to this repository, if any of those interest you. If you want to create your own you can use the [[https://github.com/purarue/HPI-template][template]] to get started. -Though, enabling this many modules may make ~hpi doctor~ look pretty busy. You can explicitly choose to enable/disable modules with a list of modules/regexes in your [[https://github.com/karlicoss/HPI/blob/f559e7cb899107538e6c6bbcf7576780604697ef/my/core/core_config.py#L24-L55][core config]], see [[https://github.com/seanbreckenridge/dotfiles/blob/a1a77c581de31bd55a6af3d11b8af588614a207e/.config/my/my/config/__init__.py#L42-L72][here]] for an example. +Though, enabling this many modules may make ~hpi doctor~ look pretty busy. You can explicitly choose to enable/disable modules with a list of modules/regexes in your [[https://github.com/karlicoss/HPI/blob/f559e7cb899107538e6c6bbcf7576780604697ef/my/core/core_config.py#L24-L55][core config]], see [[https://github.com/purarue/dotfiles/blob/a1a77c581de31bd55a6af3d11b8af588614a207e/.config/my/my/config/__init__.py#L42-L72][here]] for an example. You may use the other modules or [[https://github.com/karlicoss/hpi-personal-overlay][my overlay]] as reference, but python packaging is already a complicated issue, before adding complexities like namespace packages and editable installs on top of it... If you're having trouble extending HPI in this fashion, you can open an issue here, preferably with a link to your code/repository and/or ~setup.py~ you're trying to use. diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org index 1e6cf8f..a573007 100644 --- a/doc/OVERLAYS.org +++ b/doc/OVERLAYS.org @@ -66,7 +66,7 @@ This basically means that modules will be searched in both paths, with overlay t ** Installing with =--use-pep517= -See here for discussion https://github.com/seanbreckenridge/reorder_editable/issues/2, but TLDR it should work similarly. +See here for discussion https://github.com/purarue/reorder_editable/issues/2, but TLDR it should work similarly. * Testing runtime behaviour (editable install) diff --git a/doc/QUERY.md b/doc/QUERY.md index b672dff..a85450a 100644 --- a/doc/QUERY.md +++ b/doc/QUERY.md @@ -99,7 +99,7 @@ Commit(committed_dt=datetime.datetime(2023, 4, 14, 23, 9, 1, tzinfo=datetime.tim authored_dt=datetime.datetime(2023, 4, 14, 23, 4, 1, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200))), message='sources.smscalls: propogate errors if there are breaking ' 'schema changes', - repo='/home/sean/Repos/promnesia-fork', + repo='/home/username/Repos/promnesia-fork', sha='22a434fca9a28df9b0915ccf16368df129d2c9ce', ref='refs/heads/smscalls-handle-result') ``` @@ -195,7 +195,7 @@ To preview, you can use something like [`qgis`](https://qgis.org/en/site/) or fo chicago trip -(Sidenote: this is [`@seanbreckenridge`](https://github.com/seanbreckenridge/)s locations, on a trip to Chicago) +(Sidenote: this is [`@purarue`](https://github.com/purarue/)s locations, on a trip to Chicago) ## Python reference @@ -301,4 +301,4 @@ The `hpi query` command is a CLI wrapper around the code in [`query.py`](../my/c If you specify a range, drop_unsorted is forced to be True ``` -Those can be imported and accept any sort of iterator, `hpi query` just defaults to the output of functions here. As an example, see [`listens`](https://github.com/seanbreckenridge/HPI-personal/blob/master/scripts/listens) which just passes an generator (iterator) as the first argument to `query_range` +Those can be imported and accept any sort of iterator, `hpi query` just defaults to the output of functions here. As an example, see [`listens`](https://github.com/purarue/HPI-personal/blob/master/scripts/listens) which just passes an generator (iterator) as the first argument to `query_range` diff --git a/doc/SETUP.org b/doc/SETUP.org index 0fced62..ee9571c 100644 --- a/doc/SETUP.org +++ b/doc/SETUP.org @@ -387,7 +387,7 @@ But there is an extra caveat: rexport is already coming with nice [[https://gith Several other HPI modules are following a similar pattern: hypothesis, instapaper, pinboard, kobo, etc. -Since the [[https://github.com/karlicoss/rexport#api-limitations][reddit API has limited results]], you can use [[https://github.com/seanbreckenridge/pushshift_comment_export][my.reddit.pushshift]] to access older reddit comments, which both then get merged into =my.reddit.all.comments= +Since the [[https://github.com/karlicoss/rexport#api-limitations][reddit API has limited results]], you can use [[https://github.com/purarue/pushshift_comment_export][my.reddit.pushshift]] to access older reddit comments, which both then get merged into =my.reddit.all.comments= ** Twitter diff --git a/misc/.flake8-karlicoss b/misc/.flake8-karlicoss index 3c98b96..5933253 100644 --- a/misc/.flake8-karlicoss +++ b/misc/.flake8-karlicoss @@ -32,6 +32,6 @@ ignore = # # as a reference: -# https://github.com/seanbreckenridge/cookiecutter-template/blob/master/%7B%7Bcookiecutter.module_name%7D%7D/setup.cfg +# https://github.com/purarue/cookiecutter-template/blob/master/%7B%7Bcookiecutter.module_name%7D%7D/setup.cfg # and this https://github.com/karlicoss/HPI/pull/151 # find ./my | entr flake8 --ignore=E402,E501,E741,W503,E266,E302,E305,E203,E261,E252,E251,E221,W291,E225,E303,E702,E202,F841,E731,E306,E127 E722,E231 my | grep -v __NOT_HPI_MODULE__ diff --git a/my/browser/active_browser.py b/my/browser/active_browser.py index 8051f1b..1686fc5 100644 --- a/my/browser/active_browser.py +++ b/my/browser/active_browser.py @@ -1,5 +1,5 @@ """ -Parses active browser history by backing it up with [[http://github.com/seanbreckenridge/sqlite_backup][sqlite_backup]] +Parses active browser history by backing it up with [[http://github.com/purarue/sqlite_backup][sqlite_backup]] """ REQUIRES = ["browserexport", "sqlite_backup"] diff --git a/my/browser/export.py b/my/browser/export.py index 351cf6e..52ade0e 100644 --- a/my/browser/export.py +++ b/my/browser/export.py @@ -1,5 +1,5 @@ """ -Parses browser history using [[http://github.com/seanbreckenridge/browserexport][browserexport]] +Parses browser history using [[http://github.com/purarue/browserexport][browserexport]] """ REQUIRES = ["browserexport"] diff --git a/my/google/takeout/parser.py b/my/google/takeout/parser.py index 80c2be1..13fd04a 100644 --- a/my/google/takeout/parser.py +++ b/my/google/takeout/parser.py @@ -1,7 +1,7 @@ """ -Parses Google Takeout using [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] +Parses Google Takeout using [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] -See [[https://github.com/seanbreckenridge/google_takeout_parser][google_takeout_parser]] for more information +See [[https://github.com/purarue/google_takeout_parser][google_takeout_parser]] for more information about how to export and organize your takeouts If the DISABLE_TAKEOUT_CACHE environment variable is set, this won't cache individual @@ -12,7 +12,7 @@ zip files of the exports, which are temporarily unpacked while creating the cachew cache """ -REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"] import os from collections.abc import Sequence @@ -36,7 +36,7 @@ from google_takeout_parser.merge import CacheResults, GoogleEventSet from google_takeout_parser.models import BaseEvent from google_takeout_parser.path_dispatch import TakeoutParser -# see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example +# see https://github.com/purarue/dotfiles/blob/master/.config/my/my/config/__init__.py for an example from my.config import google as user_config @@ -123,7 +123,7 @@ def events(disable_takeout_cache: bool = DISABLE_TAKEOUT_CACHE) -> CacheResults: else: results = exit_stack.enter_context(match_structure(path, expected=EXPECTED, partial=True)) for m in results: - # e.g. /home/sean/data/google_takeout/Takeout-1634932457.zip") -> 'Takeout-1634932457' + # e.g. /home/username/data/google_takeout/Takeout-1634932457.zip") -> 'Takeout-1634932457' # means that zipped takeouts have nice filenames from cachew cw_id, _, _ = path.name.rpartition(".") # each takeout result is cached as well, in individual databases per-type diff --git a/my/ip/all.py b/my/ip/all.py index e8277c1..c267383 100644 --- a/my/ip/all.py +++ b/my/ip/all.py @@ -3,10 +3,10 @@ An example all.py stub module that provides ip data To use this, you'd add IP providers that yield IPs to the 'ips' function -For an example of how this could be used, see https://github.com/seanbreckenridge/HPI/tree/master/my/ip +For an example of how this could be used, see https://github.com/purarue/HPI/tree/master/my/ip """ -REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] +REQUIRES = ["git+https://github.com/purarue/ipgeocache"] from collections.abc import Iterator diff --git a/my/ip/common.py b/my/ip/common.py index ef54ee3..b551281 100644 --- a/my/ip/common.py +++ b/my/ip/common.py @@ -1,5 +1,5 @@ """ -Provides location/timezone data from IP addresses, using [[https://github.com/seanbreckenridge/ipgeocache][ipgeocache]] +Provides location/timezone data from IP addresses, using [[https://github.com/purarue/ipgeocache][ipgeocache]] """ from my.core import __NOT_HPI_MODULE__ # isort: skip diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index 732af67..8b50878 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -2,7 +2,7 @@ Converts IP addresses provided by my.location.ip to estimated locations """ -REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] +REQUIRES = ["git+https://github.com/purarue/ipgeocache"] from dataclasses import dataclass from datetime import timedelta diff --git a/my/location/google_takeout.py b/my/location/google_takeout.py index cb5bef3..8613257 100644 --- a/my/location/google_takeout.py +++ b/my/location/google_takeout.py @@ -2,7 +2,7 @@ Extracts locations using google_takeout_parser -- no shared code with the deprecated my.location.google """ -REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"] from collections.abc import Iterator diff --git a/my/location/google_takeout_semantic.py b/my/location/google_takeout_semantic.py index 7bddfa8..e84a932 100644 --- a/my/location/google_takeout_semantic.py +++ b/my/location/google_takeout_semantic.py @@ -5,7 +5,7 @@ Extracts semantic location history using google_takeout_parser # This is a separate module to prevent ImportError and a new config block from breaking # previously functional my.location.google_takeout locations -REQUIRES = ["git+https://github.com/seanbreckenridge/google_takeout_parser"] +REQUIRES = ["git+https://github.com/purarue/google_takeout_parser"] from collections.abc import Iterator from dataclasses import dataclass diff --git a/my/location/via_ip.py b/my/location/via_ip.py index d465ad0..240ec5f 100644 --- a/my/location/via_ip.py +++ b/my/location/via_ip.py @@ -1,4 +1,4 @@ -REQUIRES = ["git+https://github.com/seanbreckenridge/ipgeocache"] +REQUIRES = ["git+https://github.com/purarue/ipgeocache"] from my.core.warnings import high diff --git a/my/reddit/pushshift.py b/my/reddit/pushshift.py index 1bfa048..12f592b 100644 --- a/my/reddit/pushshift.py +++ b/my/reddit/pushshift.py @@ -1,11 +1,11 @@ """ Gives you access to older comments possibly not accessible with rexport using pushshift -See https://github.com/seanbreckenridge/pushshift_comment_export +See https://github.com/purarue/pushshift_comment_export """ REQUIRES = [ - "git+https://github.com/seanbreckenridge/pushshift_comment_export", + "git+https://github.com/purarue/pushshift_comment_export", ] from dataclasses import dataclass @@ -21,7 +21,7 @@ from my.core.cfg import make_config @dataclass class pushshift_config(uconfig.pushshift): ''' - Uses [[https://github.com/seanbreckenridge/pushshift_comment_export][pushshift]] to get access to old comments + Uses [[https://github.com/purarue/pushshift_comment_export][pushshift]] to get access to old comments ''' # path[s]/glob to the exported JSON data From ad55c5c345888abaebf59ae85923339b7ceccbb4 Mon Sep 17 00:00:00 2001 From: Srajan Garg Date: Tue, 12 Nov 2024 19:05:27 -0500 Subject: [PATCH 49/55] fix typo in rexport DAL (#405) * fix typo in rexport DAL --- my/reddit/rexport.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/my/reddit/rexport.py b/my/reddit/rexport.py index cb6af01..262635b 100644 --- a/my/reddit/rexport.py +++ b/my/reddit/rexport.py @@ -146,7 +146,7 @@ if not TYPE_CHECKING: # here we just check that types are available, we don't actually want to import them # fmt: off dal.Subreddit # noqa: B018 - dal.Profil # noqa: B018e + dal.Profile # noqa: B018 dal.Multireddit # noqa: B018 # fmt: on except AttributeError as ae: From a7f05c2cad0c500210f966e0f50e0b309490cc53 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Wed, 20 Nov 2024 00:03:40 -0800 Subject: [PATCH 50/55] doc: spelling fixes --- CHANGELOG.md | 2 +- doc/OVERLAYS.org | 6 +++--- doc/QUERY.md | 2 +- my/core/cachew.py | 2 +- my/core/konsume.py | 2 +- my/core/logging.py | 2 +- my/core/tests/test_tmp_config.py | 2 +- my/core/utils/itertools.py | 4 ++-- my/fbmessenger/__init__.py | 2 +- my/fbmessenger/android.py | 2 +- my/instagram/all.py | 2 +- my/instagram/gdpr.py | 4 ++-- my/reddit/__init__.py | 2 +- my/smscalls.py | 4 ++-- my/stackexchange/gdpr.py | 2 +- my/time/tz/via_location.py | 2 +- my/tinder/android.py | 2 +- my/topcoder.py | 2 +- my/twitter/android.py | 2 +- my/twitter/twint.py | 2 +- my/whatsapp/android.py | 2 +- my/youtube/takeout.py | 2 +- 22 files changed, 27 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dd19df..d60ef35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ General/my.core changes: - e81dddddf083ffd81aa7e2b715bd34f59949479c properly resolve class properties in make_config + add test Modules: -- some innitial work on filling **InfluxDB** with HPI data +- some initial work on filling **InfluxDB** with HPI data - pinboard - 42399f6250d9901d93dcedcfe05f7857babcf834: **breaking backwards compatibility**, use pinbexport module directly diff --git a/doc/OVERLAYS.org b/doc/OVERLAYS.org index a573007..7bafa48 100644 --- a/doc/OVERLAYS.org +++ b/doc/OVERLAYS.org @@ -10,7 +10,7 @@ Relevant discussion about overlays: https://github.com/karlicoss/HPI/issues/102 # You can see them TODO in overlays dir -Consider a toy package/module structure with minimal code, wihout any actual data parsing, just for demonstration purposes. +Consider a toy package/module structure with minimal code, without any actual data parsing, just for demonstration purposes. - =main= package structure # TODO do links @@ -19,7 +19,7 @@ Consider a toy package/module structure with minimal code, wihout any actual dat Extracts Twitter data from GDPR archive. - =my/twitter/all.py= Merges twitter data from multiple sources (only =gdpr= in this case), so data consumers are agnostic of specific data sources used. - This will be overriden by =overlay=. + This will be overridden by =overlay=. - =my/twitter/common.py= Contains helper function to merge data, so they can be reused by overlay's =all.py=. - =my/reddit.py= @@ -126,7 +126,7 @@ https://github.com/python/mypy/blob/1dd8e7fe654991b01bd80ef7f1f675d9e3910c3a/myp For now, I opened an issue in mypy repository https://github.com/python/mypy/issues/16683 -But ok, maybe mypy treats =main= as an external package somhow but still type checks it properly? +But ok, maybe mypy treats =main= as an external package somehow but still type checks it properly? Let's see what's going on with imports: : $ mypy --namespace-packages --strict -p my --follow-imports=error diff --git a/doc/QUERY.md b/doc/QUERY.md index a85450a..9a5d9d3 100644 --- a/doc/QUERY.md +++ b/doc/QUERY.md @@ -97,7 +97,7 @@ By default, this just returns the items in the order they were returned by the f hpi query my.coding.commits.commits --order-key committed_dt --limit 1 --reverse --output pprint --stream Commit(committed_dt=datetime.datetime(2023, 4, 14, 23, 9, 1, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200))), authored_dt=datetime.datetime(2023, 4, 14, 23, 4, 1, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200))), - message='sources.smscalls: propogate errors if there are breaking ' + message='sources.smscalls: propagate errors if there are breaking ' 'schema changes', repo='/home/username/Repos/promnesia-fork', sha='22a434fca9a28df9b0915ccf16368df129d2c9ce', diff --git a/my/core/cachew.py b/my/core/cachew.py index 9ccee09..8ce2f2b 100644 --- a/my/core/cachew.py +++ b/my/core/cachew.py @@ -136,7 +136,7 @@ if TYPE_CHECKING: CC = Callable[P, R] # need to give it a name, if inlined into bound=, mypy runs in a bug PathProvider = Union[PathIsh, Callable[P, PathIsh]] # NOTE: in cachew, HashFunction type returns str - # however in practice, cachew alwasy calls str for its result + # however in practice, cachew always calls str for its result # so perhaps better to switch it to Any in cachew as well HashFunction = Callable[P, Any] diff --git a/my/core/konsume.py b/my/core/konsume.py index 6d24167..41b5a4e 100644 --- a/my/core/konsume.py +++ b/my/core/konsume.py @@ -236,7 +236,7 @@ def test_zoom() -> None: # - very flexible, easy to adjust behaviour # - cons: # - can forget to assert about extra entities etc, so error prone -# - if we do something like =assert j.pop('status') == 200, j=, by the time assert happens we already popped item -- makes erro handling harder +# - if we do something like =assert j.pop('status') == 200, j=, by the time assert happens we already popped item -- makes error handling harder # - a bit verbose.. so probably requires some helper functions though (could be much leaner than current konsume though) # - if we assert, then terminates parsing too early, if we're defensive then inflates the code a lot with if statements # - TODO perhaps combine warnings somehow or at least only emit once per module? diff --git a/my/core/logging.py b/my/core/logging.py index bdee9aa..167a167 100644 --- a/my/core/logging.py +++ b/my/core/logging.py @@ -250,7 +250,7 @@ if __name__ == '__main__': test() -## legacy/deprecated methods for backwards compatilibity +## legacy/deprecated methods for backwards compatibility if not TYPE_CHECKING: from .compat import deprecated diff --git a/my/core/tests/test_tmp_config.py b/my/core/tests/test_tmp_config.py index e5a24cc..d99621d 100644 --- a/my/core/tests/test_tmp_config.py +++ b/my/core/tests/test_tmp_config.py @@ -12,7 +12,7 @@ def _init_default_config() -> None: def test_tmp_config() -> None: ## ugh. ideally this would be on the top level (would be a better test) - ## but pytest imports eveything first, executes hooks, and some reset_modules() fictures mess stuff up + ## but pytest imports everything first, executes hooks, and some reset_modules() fictures mess stuff up ## later would be nice to be a bit more careful about them _init_default_config() from my.simple import items diff --git a/my/core/utils/itertools.py b/my/core/utils/itertools.py index 501ebbe..42b2b77 100644 --- a/my/core/utils/itertools.py +++ b/my/core/utils/itertools.py @@ -321,7 +321,7 @@ _UET = TypeVar('_UET') _UEU = TypeVar('_UEU') -# NOTE: for historic reasons, this function had to accept Callable that retuns iterator +# NOTE: for historic reasons, this function had to accept Callable that returns iterator # instead of just iterator # TODO maybe deprecated Callable support? not sure def unique_everseen( @@ -358,7 +358,7 @@ def test_unique_everseen() -> None: assert list(unique_everseen(fun_good)) == [123] with pytest.raises(Exception): - # since function retuns a list rather than iterator, check happens immediately + # since function returns a list rather than iterator, check happens immediately # , even without advancing the iterator unique_everseen(fun_bad) diff --git a/my/fbmessenger/__init__.py b/my/fbmessenger/__init__.py index f729de9..e5e417c 100644 --- a/my/fbmessenger/__init__.py +++ b/my/fbmessenger/__init__.py @@ -9,7 +9,7 @@ since that allows for easier overriding using namespace packages See https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#allpy for more info. """ -# prevent it from apprearing in modules list/doctor +# prevent it from appearing in modules list/doctor from ..core import __NOT_HPI_MODULE__ # kinda annoying to keep it, but it's so legacy 'hpi module install my.fbmessenger' works diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index a16d924..db4cc54 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -174,7 +174,7 @@ def _process_db_msys(db: sqlite3.Connection) -> Iterator[Res[Entity]]: However seems that when message is not sent yet it doesn't have this server id yet (happened only once, but could be just luck of course!) We exclude these messages to avoid duplication. - However poisitive filter (e.g. message_id LIKE 'mid%') feels a bit wrong, e.g. what if mesage ids change or something + However poisitive filter (e.g. message_id LIKE 'mid%') feels a bit wrong, e.g. what if message ids change or something So instead this excludes only such unsent messages. */ message_id != offline_threading_id diff --git a/my/instagram/all.py b/my/instagram/all.py index 214e6ac..ce78409 100644 --- a/my/instagram/all.py +++ b/my/instagram/all.py @@ -23,7 +23,7 @@ def messages() -> Iterator[Res[Message]]: # TODO in general best to prefer android, it has more data # - message ids # - usernames are correct for Android data - # - thread ids more meaninful? + # - thread ids more meaningful? # but for now prefer gdpr prefix since it makes a bit things a bit more consistent? # e.g. a new batch of android exports can throw off ids if we rely on it for mapping yield from _merge_messages( diff --git a/my/instagram/gdpr.py b/my/instagram/gdpr.py index 7454a04..d417fdb 100644 --- a/my/instagram/gdpr.py +++ b/my/instagram/gdpr.py @@ -76,7 +76,7 @@ def _entities() -> Iterator[Res[User | _Message]]: # NOTE: here there are basically two options # - process inputs as is (from oldest to newest) # this would be more stable wrt newer exports (e.g. existing thread ids won't change) - # the downside is that newer exports seem to have better thread ids, so might be preferrable to use them + # the downside is that newer exports seem to have better thread ids, so might be preferable to use them # - process inputs reversed (from newest to oldest) # the upside is that thread ids/usernames might be better # the downside is that if for example the user renames, thread ids will change _a lot_, might be undesirable.. @@ -137,7 +137,7 @@ def _entitites_from_path(path: Path) -> Iterator[Res[User | _Message]]: j = json.loads(ffile.read_text()) id_len = 10 - # NOTE: I'm not actually sure it's other user's id.., since it corresponds to the whole converstation + # NOTE: I'm not actually sure it's other user's id.., since it corresponds to the whole conversation # but I stared a bit at these ids vs database ids and can't see any way to find the correspondence :( # so basically the only way to merge is to actually try some magic and correlate timestamps/message texts? # another option is perhaps to query user id from username with some free API diff --git a/my/reddit/__init__.py b/my/reddit/__init__.py index f344eeb..982901a 100644 --- a/my/reddit/__init__.py +++ b/my/reddit/__init__.py @@ -9,7 +9,7 @@ since that allows for easier overriding using namespace packages See https://github.com/karlicoss/HPI/blob/master/doc/MODULE_DESIGN.org#allpy for more info. """ -# prevent it from apprearing in modules list/doctor +# prevent it from appearing in modules list/doctor from ..core import __NOT_HPI_MODULE__ # kinda annoying to keep it, but it's so legacy 'hpi module install my.reddit' works diff --git a/my/smscalls.py b/my/smscalls.py index ccaac72..324bc44 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -186,7 +186,7 @@ class MMS(NamedTuple): for (addr, _type) in self.addresses: if _type == 137: return addr - # hmm, maybe return instead? but this probably shouldnt happen, means + # hmm, maybe return instead? but this probably shouldn't happen, means # something is very broken raise RuntimeError(f'No from address matching 137 found in {self.addresses}') @@ -214,7 +214,7 @@ def mms() -> Iterator[Res[MMS]]: def _resolve_null_str(value: str | None) -> str | None: if value is None: return None - # hmm.. theres some risk of the text actually being 'null', but theres + # hmm.. there's some risk of the text actually being 'null', but there's # no way to distinguish that from XML values if value == 'null': return None diff --git a/my/stackexchange/gdpr.py b/my/stackexchange/gdpr.py index 78987be..8ed0d30 100644 --- a/my/stackexchange/gdpr.py +++ b/my/stackexchange/gdpr.py @@ -49,7 +49,7 @@ class Vote(NamedTuple): # hmm, this loads very raw comments without the rest of the page? # - https://meta.stackexchange.com/posts/27319/comments#comment-57475 # - # parentPostId is the original quesion + # parentPostId is the original question # TODO is not always present? fucking hell # seems like there is no way to get a hierarchical comment link.. guess this needs to be handled in Promnesia normalisation... # postId is the answer diff --git a/my/time/tz/via_location.py b/my/time/tz/via_location.py index 58b5bf7..1b2275b 100644 --- a/my/time/tz/via_location.py +++ b/my/time/tz/via_location.py @@ -245,7 +245,7 @@ def _iter_tzs() -> Iterator[DayWithZone]: def _day2zone() -> dict[date, pytz.BaseTzInfo]: # NOTE: kinda unfortunate that this will have to process all days before returning result for just one # however otherwise cachew cache might never be initialized properly - # so we'll always end up recomputing everyting during subsequent runs + # so we'll always end up recomputing everything during subsequent runs return {dz.day: pytz.timezone(dz.zone) for dz in _iter_tzs()} diff --git a/my/tinder/android.py b/my/tinder/android.py index a09794f..5a5d887 100644 --- a/my/tinder/android.py +++ b/my/tinder/android.py @@ -106,7 +106,7 @@ def _handle_db(db: sqlite3.Connection) -> Iterator[Res[_Entity]]: user_profile_rows = list(db.execute('SELECT * FROM profile_user_view')) if len(user_profile_rows) == 0: - # shit, sometime in 2023 profile_user_view stoppped containing user profile.. + # shit, sometime in 2023 profile_user_view stopped containing user profile.. # presumably the most common from_id/to_id would be our own username counter = Counter([id_ for (id_,) in db.execute('SELECT from_id FROM message UNION ALL SELECT to_id FROM message')]) if len(counter) > 0: # this might happen if db is empty (e.g. user got logged out) diff --git a/my/topcoder.py b/my/topcoder.py index 56403e2..40df77c 100644 --- a/my/topcoder.py +++ b/my/topcoder.py @@ -81,7 +81,7 @@ def _parse_one(p: Path) -> Iterator[Res[Competition]]: # but also expects cooperation from .make method (e.g. popping items from the dict) # could also wrap in helper and pass to .make .. not sure # an argument could be made that .make isn't really a class methond.. - # it's pretty specific to this parser onl + # it's pretty specific to this parser only yield from Competition.make(j=c) yield from m.check() diff --git a/my/twitter/android.py b/my/twitter/android.py index 88c9389..8159ee7 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -192,7 +192,7 @@ def get_own_user_id(conn) -> str: # - timeline_data_type # 1 : the bulk of tweets, but also some notifications etc?? # 2 : who-to-follow/community-to-join. contains a couple of tweets, but their corresponding status_id is NULL -# 8 : who-to-follow/notfication +# 8 : who-to-follow/notification # 13: semantic-core/who-to-follow # 14: cursor # 17: trends diff --git a/my/twitter/twint.py b/my/twitter/twint.py index 5106923..9d36a93 100644 --- a/my/twitter/twint.py +++ b/my/twitter/twint.py @@ -54,7 +54,7 @@ class Tweet(NamedTuple): # https://github.com/thomasancheriyil/Red-Tide-Detection-based-on-Twitter/blob/beb200be60cc66dcbc394e670513715509837812/python/twitterGapParse.py#L61-L62 # # twint is also saving 'timezone', but this is local machine timezone at the time of scraping? - # perhaps they thought date-time-ms was local time... or just kept it just in case (they are keepin lots on unnecessary stuff in the db) + # perhaps they thought date-time-ms was local time... or just kept it just in case (they are keeping lots on unnecessary stuff in the db) return datetime.fromtimestamp(seconds, tz=tz) @property diff --git a/my/whatsapp/android.py b/my/whatsapp/android.py index 3cd4436..a8dbe8d 100644 --- a/my/whatsapp/android.py +++ b/my/whatsapp/android.py @@ -199,7 +199,7 @@ def _process_db(db: sqlite3.Connection) -> Iterator[Entity]: sender_row_id = r['sender_jid_row_id'] if sender_row_id == 0: # seems that it's always 0 for 1-1 chats - # for group chats our onw id is still 0, but other ids are properly set + # for group chats our own id is still 0, but other ids are properly set if from_me: myself_user_id = config.my_user_id or 'MYSELF_USER_ID' sender = Sender(id=myself_user_id, name=None) # TODO set my own name as well? diff --git a/my/youtube/takeout.py b/my/youtube/takeout.py index 703715f..8eca328 100644 --- a/my/youtube/takeout.py +++ b/my/youtube/takeout.py @@ -36,7 +36,7 @@ def watched() -> Iterator[Res[Watched]]: continue # older exports (e.g. html) didn't have microseconds - # wheras newer json ones do have them + # whereas newer json ones do have them # seconds resolution is enough to distinguish watched videos # also we're processing takeouts in HPI in reverse order, so first seen watch would contain microseconds, resulting in better data without_microsecond = w.when.replace(microsecond=0) From 95a16b956f8ab24bea3002d1428c0c10b30a3455 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Tue, 26 Nov 2024 13:53:10 -0800 Subject: [PATCH 51/55] doc: some performance notes for query_range (#409) * doc: some performance notes for query_range * add ruff_cache to gitignore --- .gitignore | 3 +++ my/core/__init__.py | 33 ++++++++++++++++++--------------- my/core/__main__.py | 3 +++ my/core/query_range.py | 4 +++- 4 files changed, 27 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index 19c3380..65ba630 100644 --- a/.gitignore +++ b/.gitignore @@ -155,6 +155,9 @@ celerybeat-schedule .dmypy.json dmypy.json +# linters +.ruff_cache/ + # Pyre type checker .pyre/ diff --git a/my/core/__init__.py b/my/core/__init__.py index cc549d5..a8a41f4 100644 --- a/my/core/__init__.py +++ b/my/core/__init__.py @@ -29,22 +29,25 @@ if not TYPE_CHECKING: __all__ = [ - 'get_files', 'PathIsh', 'Paths', - 'Json', - 'make_logger', - 'LazyLogger', # legacy import - 'warn_if_empty', - 'stat', 'Stats', - 'datetime_aware', 'datetime_naive', - 'assert_never', # TODO maybe deprecate from use in my.core? will be in stdlib soon - - 'make_config', - '__NOT_HPI_MODULE__', - - 'Res', 'unwrap', 'notnone', - - 'dataclass', 'Path', + 'Json', + 'LazyLogger', # legacy import + 'Path', + 'PathIsh', + 'Paths', + 'Res', + 'Stats', + 'assert_never', # TODO maybe deprecate from use in my.core? will be in stdlib soon + 'dataclass', + 'datetime_aware', + 'datetime_naive', + 'get_files', + 'make_config', + 'make_logger', + 'notnone', + 'stat', + 'unwrap', + 'warn_if_empty', ] diff --git a/my/core/__main__.py b/my/core/__main__.py index 00ac4ee..7e2d8f9 100644 --- a/my/core/__main__.py +++ b/my/core/__main__.py @@ -538,6 +538,9 @@ def query_hpi_functions( # chain list of functions from user, in the order they wrote them on the CLI input_src = chain(*(f() for f in _locate_functions_or_prompt(qualified_names))) + # NOTE: if passing just one function to this which returns a single namedtuple/dataclass, + # using both --order-key and --order-type will often be faster as it does not need to + # duplicate the iterator in memory, or try to find the --order-type type on each object before sorting res = select_range( input_src, order_key=order_key, diff --git a/my/core/query_range.py b/my/core/query_range.py index 2a8d7bd..83728bf 100644 --- a/my/core/query_range.py +++ b/my/core/query_range.py @@ -337,6 +337,8 @@ def select_range( # if the user supplied a order_key, and/or we've generated an order_value, create # the function that accesses that type on each value in the iterator if order_key is not None or order_value is not None: + # _generate_order_value_func internally here creates a copy of the iterator, which has to + # be consumed in-case we're sorting by mixed types order_by_chosen, itr = _handle_generate_order_by(itr, order_key=order_key, order_value=order_value) # signifies that itr is empty -- can early return here if order_by_chosen is None: @@ -398,7 +400,7 @@ Specify a type or a key to order the value by""") return itr -# re-use items from query for testing +# reuse items from query for testing from .query import _A, _B, _Float, _mixed_iter_errors From d8c53bde34e2a5e68f2bac18941ae426ed468b02 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Mon, 25 Nov 2024 16:31:22 -0800 Subject: [PATCH 52/55] smscalls: add phone number to model --- my/smscalls.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/my/smscalls.py b/my/smscalls.py index 324bc44..0ff2553 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -37,6 +37,7 @@ class Call(NamedTuple): dt: datetime dt_readable: str duration_s: int + phone_number: str who: str | None # type - 1 = Incoming, 2 = Outgoing, 3 = Missed, 4 = Voicemail, 5 = Rejected, 6 = Refused List. call_type: int @@ -65,12 +66,13 @@ def _extract_calls(path: Path) -> Iterator[Res[Call]]: duration = cxml.get('duration') who = cxml.get('contact_name') call_type = cxml.get('type') + number = cxml.get('number') # if name is missing, its not None (its some string), depends on the phone/message app if who is not None and who in UNKNOWN: who = None - if dt is None or dt_readable is None or duration is None or call_type is None: + if dt is None or dt_readable is None or duration is None or call_type is None or number is None: call_str = etree.tostring(cxml).decode('utf-8') - yield RuntimeError(f"Missing one or more required attributes [date, readable_date, duration, type] in {call_str}") + yield RuntimeError(f"Missing one or more required attributes [date, readable_date, duration, type, number] in {call_str}") continue # TODO we've got local tz here, not sure if useful.. # ok, so readable date is local datetime, changing throughout the backup @@ -78,6 +80,7 @@ def _extract_calls(path: Path) -> Iterator[Res[Call]]: dt=_parse_dt_ms(dt), dt_readable=dt_readable, duration_s=int(duration), + phone_number=number, who=who, call_type=int(call_type), ) From f1d23c5e96d95819d383485f22b480d8d190fe98 Mon Sep 17 00:00:00 2001 From: purarue <7804791+purarue@users.noreply.github.com> Date: Sun, 22 Dec 2024 21:50:03 -0800 Subject: [PATCH 53/55] smscalls: allow large XML files as input once XML files increase past a certain size (was about 220MB for me), the parser just throws an error because the tree is too large (iirc for security reasons) could maybe look at using iterparse in the future to parse it without loading the whole file, but this seems to fix it fine for me --- my/smscalls.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/my/smscalls.py b/my/smscalls.py index 0ff2553..27d08be 100644 --- a/my/smscalls.py +++ b/my/smscalls.py @@ -57,9 +57,12 @@ class Call(NamedTuple): # The '(Unknown)' is just what my android phone does, not sure if there are others UNKNOWN: set[str] = {'(Unknown)'} +def _parse_xml(xml: Path) -> Any: + return etree.parse(str(xml), parser=etree.XMLParser(huge_tree=True)) + def _extract_calls(path: Path) -> Iterator[Res[Call]]: - tr = etree.parse(str(path)) + tr = _parse_xml(path) for cxml in tr.findall('call'): dt = cxml.get('date') dt_readable = cxml.get('readable_date') @@ -133,7 +136,7 @@ def messages() -> Iterator[Res[Message]]: def _extract_messages(path: Path) -> Iterator[Res[Message]]: - tr = etree.parse(str(path)) + tr = _parse_xml(path) for mxml in tr.findall('sms'): dt = mxml.get('date') dt_readable = mxml.get('readable_date') @@ -225,8 +228,7 @@ def _resolve_null_str(value: str | None) -> str | None: def _extract_mms(path: Path) -> Iterator[Res[MMS]]: - tr = etree.parse(str(path)) - + tr = _parse_xml(path) for mxml in tr.findall('mms'): dt = mxml.get('date') dt_readable = mxml.get('readable_date') @@ -271,10 +273,7 @@ def _extract_mms(path: Path) -> Iterator[Res[MMS]]: # # This seems pretty useless, so we should try and skip it, and just return the # text/images/data - # - # man, attrib is some internal cpython ._Attrib type which can't - # be typed by any sort of mappingproxy. maybe a protocol could work..? - part_data: dict[str, Any] = part.attrib # type: ignore + part_data: dict[str, Any] = part.attrib seq: str | None = part_data.get('seq') if seq == '-1': continue From 54df429f614a5e5d0617dcd196bf8566608e987c Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 29 Dec 2024 15:06:49 +0000 Subject: [PATCH 54/55] core.sqlite: add helper SqliteTool to get table schemas --- my/core/sqlite.py | 43 +++++++++++++++++++++++++++++++++++++++ my/fbmessenger/android.py | 4 ++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/my/core/sqlite.py b/my/core/sqlite.py index aa41ab3..6167d2e 100644 --- a/my/core/sqlite.py +++ b/my/core/sqlite.py @@ -134,3 +134,46 @@ def select(cols: tuple[str, str, str, str, str, str, str, str], rest: str, *, db def select(cols, rest, *, db): # db arg is last cause that results in nicer code formatting.. return db.execute('SELECT ' + ','.join(cols) + ' ' + rest) + + +class SqliteTool: + def __init__(self, connection: sqlite3.Connection) -> None: + self.connection = connection + + def _get_sqlite_master(self) -> dict[str, str]: + res = {} + for c in self.connection.execute('SELECT name, type FROM sqlite_master'): + [name, type_] = c + assert type_ in {'table', 'index', 'view', 'trigger'}, (name, type_) # just in case + res[name] = type_ + return res + + def get_table_names(self) -> list[str]: + master = self._get_sqlite_master() + res = [] + for name, type_ in master.items(): + if type_ != 'table': + continue + res.append(name) + return res + + def get_table_schema(self, name: str) -> dict[str, str]: + """ + Returns map from column name to column type + + NOTE: Sometimes this doesn't work if the db has some extensions (e.g. happens for facebook apps) + In this case you might still be able to use get_table_names + """ + schema: dict[str, str] = {} + for row in self.connection.execute(f'PRAGMA table_info(`{name}`)'): + col = row[1] + type_ = row[2] + # hmm, somewhere between 3.34.1 and 3.37.2, sqlite started normalising type names to uppercase + # let's do this just in case since python < 3.10 are using the old version + # e.g. it could have returned 'blob' and that would confuse blob check (see _check_allowed_blobs) + type_ = type_.upper() + schema[col] = type_ + return schema + + def get_table_schemas(self) -> dict[str, dict[str, str]]: + return {name: self.get_table_schema(name) for name in self.get_table_names()} diff --git a/my/fbmessenger/android.py b/my/fbmessenger/android.py index db4cc54..f6fdb82 100644 --- a/my/fbmessenger/android.py +++ b/my/fbmessenger/android.py @@ -15,7 +15,7 @@ from my.core import LazyLogger, Paths, Res, datetime_aware, get_files, make_conf from my.core.common import unique_everseen from my.core.compat import assert_never from my.core.error import echain -from my.core.sqlite import sqlite_connection +from my.core.sqlite import sqlite_connection, SqliteTool from my.config import fbmessenger as user_config # isort: skip @@ -86,8 +86,8 @@ def _entities() -> Iterator[Res[Entity]]: for idx, path in enumerate(paths): logger.info(f'processing [{idx:>{width}}/{total:>{width}}] {path}') with sqlite_connection(path, immutable=True, row_factory='row') as db: + use_msys = "logging_events_v2" in SqliteTool(db).get_table_names() try: - use_msys = len(list(db.execute('SELECT * FROM sqlite_master WHERE name = "logging_events_v2"'))) > 0 if use_msys: yield from _process_db_msys(db) else: From bb703c8c6a7ef80205030f640316c222bc48a6e1 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 29 Dec 2024 15:37:10 +0000 Subject: [PATCH 55/55] twitter.android: fix get_own_user_id for latest exports --- my/twitter/android.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/my/twitter/android.py b/my/twitter/android.py index 8159ee7..7e8f170 100644 --- a/my/twitter/android.py +++ b/my/twitter/android.py @@ -161,9 +161,22 @@ def get_own_user_id(conn) -> str: 'SELECT DISTINCT CAST(list_mapping_user_id AS TEXT) FROM list_mapping', 'SELECT DISTINCT CAST(owner_id AS TEXT) FROM cursors', 'SELECT DISTINCT CAST(user_id AS TEXT) FROM users WHERE _id == 1', + # ugh, sometimes all of the above are empty... + # for the rest it seems: + # - is_active_creator is NULL + # - is_graduated is NULL + # - profile_highlighted_info is NULL + 'SELECT DISTINCT CAST(user_id AS TEXT) FROM users WHERE is_active_creator == 0 AND is_graduated == 1 AND profile_highlights_info IS NOT NULL', ]: - for (r,) in conn.execute(q): - res.add(r) + res |= {r for (r,) in conn.execute(q)} + + assert len(res) <= 1, res + if len(res) == 0: + # sometimes even all of the above doesn't help... + # last resort is trying to get from status_groups table + # however we can't always use it because it might contain multiple different owner_id? + # not sure, maybe it will break as well and we'll need to fallback on the most common or something.. + res |= {r for (r,) in conn.execute('SELECT DISTINCT CAST(owner_id AS TEXT) FROM status_groups')} assert len(res) == 1, res [r] = res return r