From d9364eea9e92d645c6226abd4074f3c764507de8 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 09:29:08 +0100 Subject: [PATCH 01/32] Set all "strict" options explicitly --- pyproject.toml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index cc4d0e5..5f26c27 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -447,6 +447,9 @@ disallow_any_generics = true # Disallow functions with incomplete type annotations disallow_incomplete_defs = true +# Allow subclassing `Any` as long as the ORM models' `Base` is untyped +disallow_subclassing_any = false + # Disallow calling functions without type annotations ... disallow_untyped_calls = true # ... except for libraries without type annotations @@ -454,12 +457,33 @@ untyped_calls_exclude = [ "folium", ] +# Disallow decorators without type annotations +disallow_untyped_decorators = true + # Disallow functions without type annotations (or incomplete annotations) disallow_untyped_defs = true # Require an error code in all "# type: ignore" comments enable_error_code = ["ignore-without-code"] +# Check further edge cases that are rarely an issue in practice +extra_checks = true + +# Treat imported names as re-exported as long as some packages lack `__all__` +no_implicit_reexport = false + +# Disallow comparisons of non-overlapping types (e.g., `str` and `int`) +strict_equality = true + +# Report `t.cast()` calls that are not needed +warn_redundant_casts = true + +# Allow returning `Any` as long as the ORM models' relationships are untyped +warn_return_any = false + +# Report "[[tool.mypy.overrides]]" sections that match no module +warn_unused_configs = true + # Report "# type: ignore" comments that are not needed anymore warn_unused_ignores = true -- 2.47.3 From e4016db9fead3f205fc146ca6129a192513b068a Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 09:30:07 +0100 Subject: [PATCH 02/32] Enable "no_implicit_reexport" Also, remove the unused `orm_exc` import alias --- pyproject.toml | 5 ++--- src/velofy/__init__.py | 7 +++++++ src/velofy/console/forecasts.py | 4 ++-- src/velofy/db/__init__.py | 19 +++++++++++++++++++ src/velofy/db/replay/__init__.py | 6 ++++++ src/velofy/db/utils/__init__.py | 7 +++++++ src/velofy/forecasts/models/__init__.py | 10 ++++++++++ 7 files changed, 53 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5f26c27..92c28e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -469,8 +469,8 @@ enable_error_code = ["ignore-without-code"] # Check further edge cases that are rarely an issue in practice extra_checks = true -# Treat imported names as re-exported as long as some packages lack `__all__` -no_implicit_reexport = false +# Treat only names listed in `__all__` as re-exported +no_implicit_reexport = true # Disallow comparisons of non-overlapping types (e.g., `str` and `int`) strict_equality = true @@ -749,7 +749,6 @@ banned-from = [ "sqlalchemy.dialects.postgresql" = "psql" "sqlalchemy.exc" = "sa_exc" "sqlalchemy.ext.hybrid" = "sa_hybrid" -"sqlalchemy.orm.exc" = "orm_exc" "statsmodels.tsa.api" = "tsa" "tests.config" = "test_config" "typing" = "t" diff --git a/src/velofy/__init__.py b/src/velofy/__init__.py index 4c513c6..cc0cd75 100644 --- a/src/velofy/__init__.py +++ b/src/velofy/__init__.py @@ -15,6 +15,13 @@ from velofy import db from velofy import forecasts +__all__ = [ + "config", + "db", + "forecasts", +] + + try: _pkg_info = _metadata.metadata(__name__) diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index e4b3fb6..c4d635f 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -10,7 +10,7 @@ import sys import click import sqlalchemy as sa -from sqlalchemy.orm import exc as orm_exc +from sqlalchemy import exc as sa_exc from velofy import config as pkg_config from velofy import db @@ -69,7 +69,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 try: city_obj = db.session.query(db.City).filter_by(name=city.title()).one() - except orm_exc.NoResultFound: + except sa_exc.NoResultFound: click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"') sys.exit(1) diff --git a/src/velofy/db/__init__.py b/src/velofy/db/__init__.py index af7a334..30fdbdf 100644 --- a/src/velofy/db/__init__.py +++ b/src/velofy/db/__init__.py @@ -15,3 +15,22 @@ from velofy.db.pixels import Pixel from velofy.db.replay import ReplayedOrder from velofy.db.replay import ReplaySimulation from velofy.db.restaurants import Restaurant + + +__all__ = [ + "Address", + "AddressPixelAssociation", + "Base", + "City", + "Courier", + "Customer", + "Forecast", + "Grid", + "Order", + "Path", + "Pixel", + "ReplaySimulation", + "ReplayedOrder", + "Restaurant", + "session", +] diff --git a/src/velofy/db/replay/__init__.py b/src/velofy/db/replay/__init__.py index 877bab1..44fee3a 100644 --- a/src/velofy/db/replay/__init__.py +++ b/src/velofy/db/replay/__init__.py @@ -2,3 +2,9 @@ from velofy.db.replay.orders import ReplayedOrder from velofy.db.replay.simulations import ReplaySimulation + + +__all__ = [ + "ReplaySimulation", + "ReplayedOrder", +] diff --git a/src/velofy/db/utils/__init__.py b/src/velofy/db/utils/__init__.py index 9d073fe..22810a5 100644 --- a/src/velofy/db/utils/__init__.py +++ b/src/velofy/db/utils/__init__.py @@ -3,3 +3,10 @@ from velofy.db.utils.colors import make_random_cmap from velofy.db.utils.colors import rgb_to_hex from velofy.db.utils.locations import Location + + +__all__ = [ + "Location", + "make_random_cmap", + "rgb_to_hex", +] diff --git a/src/velofy/forecasts/models/__init__.py b/src/velofy/forecasts/models/__init__.py index 17b16b2..06ce7a1 100644 --- a/src/velofy/forecasts/models/__init__.py +++ b/src/velofy/forecasts/models/__init__.py @@ -35,3 +35,13 @@ from velofy.forecasts.models.tactical.horizontal import HorizontalSMAModel from velofy.forecasts.models.tactical.other import TrivialModel from velofy.forecasts.models.tactical.realtime import RealtimeARIMAModel from velofy.forecasts.models.tactical.vertical import VerticalARIMAModel + + +__all__ = [ + "ForecastingModelABC", + "HorizontalETSModel", + "HorizontalSMAModel", + "RealtimeARIMAModel", + "TrivialModel", + "VerticalARIMAModel", +] -- 2.47.3 From ef0888619efdc18a75b05133c9e863e78d590c15 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:03:56 +0100 Subject: [PATCH 03/32] Enable PYI019 and PYI034 --- pyproject.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 92c28e4..28d62be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -301,6 +301,8 @@ select = [ # "PL", # flake8-use-pathlib => `pathlib` instead of `os` functions # "PTH", + # flake8-pyi (only two codes) => `t.Self` instead of the class name + # "PYI019", "PYI034", # Ruff-specific rules => Fewer bugs and cleaner code # "RUF", # flake8-self => No access to private members from outside @@ -646,6 +648,8 @@ select = [ "PL", # flake8-use-pathlib => `pathlib` instead of `os` functions "PTH", + # flake8-pyi (only two codes) => `t.Self` instead of the class name + "PYI019", "PYI034", # Ruff-specific rules => Fewer bugs and cleaner code "RUF", # flake8-self => No access to private members from outside -- 2.47.3 From cd74b343bc258445d46457950741bc8deaf96774 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 10:30:05 +0100 Subject: [PATCH 04/32] Replace the `__future__` imports ... ... with quoted annotations where needed --- src/velofy/db/addresses.py | 4 +--- src/velofy/db/addresses_addresses.py | 6 ++---- src/velofy/db/cities.py | 4 +--- src/velofy/db/customers.py | 4 +--- src/velofy/db/forecasts.py | 6 ++---- src/velofy/db/grids.py | 6 ++---- src/velofy/db/pixels.py | 6 ++---- src/velofy/db/replay/orders.py | 10 ++++------ src/velofy/db/restaurants.py | 4 +--- src/velofy/db/utils/locations.py | 4 +--- src/velofy/forecasts/timify.py | 4 +--- 11 files changed, 18 insertions(+), 40 deletions(-) diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 0c16f2c..4da9292 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -1,7 +1,5 @@ """Provide the ORM's `Address` model.""" -from __future__ import annotations - import datetime as dt import functools import typing as t @@ -171,7 +169,7 @@ class Address(meta.Base): """ return self.location.y - def clear_map(self) -> Address: # pragma: no cover + def clear_map(self) -> "Address": # pragma: no cover """Shortcut to the `.city.clear_map()` method. Returns: diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 9defe93..892ef4c 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -1,7 +1,5 @@ """Model for the `Path` relationship between two `Address` objects.""" -from __future__ import annotations - import functools import itertools import json @@ -126,7 +124,7 @@ class Path(meta.Base): cls, *addresses: db.Address, google_maps: bool = False, - ) -> list[Path]: + ) -> list["Path"]: """Calculate pair-wise paths for `Address` objects. This is the main constructor method for the class. @@ -183,7 +181,7 @@ class Path(meta.Base): return paths @classmethod - def from_order(cls, order: db.Order, *, google_maps: bool = False) -> Path: + def from_order(cls, order: "db.Order", *, google_maps: bool = False) -> "Path": """Calculate the path for an `Order` object. The path goes from the `Order.pickup_address` to the `Order.delivery_address`. diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index a6fc363..2c2bcb7 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -1,7 +1,5 @@ """Provide the ORM's `City` model.""" -from __future__ import annotations - import functools import folium @@ -120,7 +118,7 @@ class City(meta.Base): """ return self.northeast.northing - self.southwest.northing - def clear_map(self) -> City: # pragma: no cover + def clear_map(self) -> "City": # pragma: no cover """Create a new `folium.Map` object aligned with the city's viewport. The map is available via the `.map` property. Note that it is mutable diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index b7b146c..25bbc35 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -1,7 +1,5 @@ """Provide the ORM's `Customer` model.""" -from __future__ import annotations - import folium import sqlalchemy as sa from sqlalchemy import orm @@ -30,7 +28,7 @@ class Customer(meta.Base): # Relationships orders = orm.relationship("Order", back_populates="customer") - def clear_map(self) -> Customer: # pragma: no cover + def clear_map(self) -> "Customer": # pragma: no cover """Shortcut to the `...city.clear_map()` method. Returns: diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 1733394..c2b24f0 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -1,7 +1,5 @@ """Provide the ORM's `Forecast` model.""" -from __future__ import annotations - import datetime as dt import math @@ -187,12 +185,12 @@ class Forecast(meta.Base): @classmethod def from_dataframe( cls, - pixel: db.Pixel, + pixel: "db.Pixel", time_step: int, train_horizon: int, model: str, data: pd.DataFrame, - ) -> list[db.Forecast]: + ) -> list["db.Forecast"]: """Convert results from the forecasting `*Model`s into `Forecast` objects. This is an alternative constructor method. diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index ec8802e..1c97748 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -1,7 +1,5 @@ """Provide the ORM's `Grid` model.""" -from __future__ import annotations - import typing as t import folium @@ -67,7 +65,7 @@ class Grid(meta.Base): return round((self.side_length**2) / 1_000_000, 1) @classmethod - def gridify(cls, city: db.City, side_length: int) -> db.Grid: + def gridify(cls, city: db.City, side_length: int) -> "db.Grid": """Create a fully populated `Grid` for a `city`. The `Grid` contains only `Pixel`s that have at least one @@ -122,7 +120,7 @@ class Grid(meta.Base): return grid - def clear_map(self) -> Grid: # pragma: no cover + def clear_map(self) -> "Grid": # pragma: no cover """Shortcut to the `.city.clear_map()` method. Returns: diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 61c5ecf..9df0314 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -1,7 +1,5 @@ """Provide the ORM's `Pixel` model.""" -from __future__ import annotations - import functools import folium @@ -130,7 +128,7 @@ class Pixel(meta.Base): return location @functools.cached_property - def restaurants(self) -> list[db.Restaurant]: # pragma: no cover + def restaurants(self) -> list["db.Restaurant"]: # pragma: no cover """Obtain all `Restaurant`s in `self`.""" return ( db.session.query(db.Restaurant) @@ -142,7 +140,7 @@ class Pixel(meta.Base): .all() ) - def clear_map(self) -> Pixel: # pragma: no cover + def clear_map(self) -> "Pixel": # pragma: no cover """Shortcut to the `.city.clear_map()` method. Returns: diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index 4e32ceb..0d990b7 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -1,7 +1,5 @@ """Provide the ORM's `ReplayedOrder` model for the replay simulations.""" -from __future__ import annotations - import datetime as dt import sqlalchemy as sa @@ -409,22 +407,22 @@ class ReplayedOrder(meta.Base): # Convenience properties @property - def customer(self) -> db.Customer: + def customer(self) -> "db.Customer": """`.customer` of the actual `Order`.""" return self.actual.customer @property - def restaurant(self) -> db.Restaurant: + def restaurant(self) -> "db.Restaurant": """`.restaurant` of the actual `Order`.""" return self.actual.restaurant @property - def pickup_address(self) -> db.Address: + def pickup_address(self) -> "db.Address": """`.pickup_address` of the actual `Order`.""" return self.actual.pickup_address @property - def delivery_address(self) -> db.Address: + def delivery_address(self) -> "db.Address": """`.delivery_address` of the actual `Order`.""" return self.actual.delivery_address diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 73bb101..733006d 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -1,7 +1,5 @@ """Provide the ORM's `Restaurant` model.""" -from __future__ import annotations - import datetime as dt import folium @@ -75,7 +73,7 @@ class Restaurant(meta.Base): """Non-literal text representation.""" return f"<{self.__class__.__name__}({self.name})>" - def clear_map(self) -> Restaurant: # pragma: no cover + def clear_map(self) -> "Restaurant": # pragma: no cover """Shortcut to the `.address.city.clear_map()` method. Returns: diff --git a/src/velofy/db/utils/locations.py b/src/velofy/db/utils/locations.py index 309f57d..e5ba650 100644 --- a/src/velofy/db/utils/locations.py +++ b/src/velofy/db/utils/locations.py @@ -1,7 +1,5 @@ """A `Location` class to unify working with coordinates.""" -from __future__ import annotations - import utm @@ -132,7 +130,7 @@ class Location: return self._normalized_northing - def relate_to(self, other: Location) -> None: + def relate_to(self, other: "Location") -> None: """Make the origin in the lower-left corner relative to `other`. The `.x` and `.y` properties are the `.easting` and `.northing` values diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 763a9f0..43119ed 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -1,7 +1,5 @@ """Obtain and work with time series data.""" -from __future__ import annotations - import datetime as dt import typing as t @@ -566,7 +564,7 @@ class OrderHistory: pixel_id: int, predict_day: dt.date, train_horizon: int, - ) -> models.ForecastingModelABC: + ) -> "models.ForecastingModelABC": """Choose the most promising forecasting `*Model` for tactical purposes. The rules are deduced from "Table 1: Top-3 models by ..." in the article -- 2.47.3 From 66330675636559c2bb5bb7d47da84ad4f667996b Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 09:43:23 +0100 Subject: [PATCH 05/32] Turn the ORM `Base` into a real class --- pyproject.toml | 4 ++-- src/velofy/db/meta.py | 11 +++++------ 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 28d62be..f45a128 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -449,8 +449,8 @@ disallow_any_generics = true # Disallow functions with incomplete type annotations disallow_incomplete_defs = true -# Allow subclassing `Any` as long as the ORM models' `Base` is untyped -disallow_subclassing_any = false +# Disallow subclassing classes typed `Any` +disallow_subclassing_any = true # Disallow calling functions without type annotations ... disallow_untyped_calls = true diff --git a/src/velofy/db/meta.py b/src/velofy/db/meta.py index 3901514..73a6a7d 100644 --- a/src/velofy/db/meta.py +++ b/src/velofy/db/meta.py @@ -1,15 +1,15 @@ """Provide the ORM's declarative base.""" -import typing as t - import sqlalchemy as sa from sqlalchemy import orm import velofy -Base: t.Any = orm.declarative_base( - metadata=sa.MetaData( +class Base(orm.DeclarativeBase): + """The declarative base of all ORM models.""" + + metadata = sa.MetaData( schema=velofy.config.CLEAN_SCHEMA, naming_convention={ "pk": "pk_%(table_name)s", @@ -18,5 +18,4 @@ Base: t.Any = orm.declarative_base( "ix": "ix_%(table_name)s_on_%(column_0_N_name)s", "ck": "ck_%(table_name)s_on_%(constraint_name)s", }, - ), -) + ) -- 2.47.3 From 2e03e58716d0312cc9f1230e6117ffaf573c6c2d Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:12:26 +0100 Subject: [PATCH 06/32] Type the relationships of `Address` --- src/velofy/db/addresses.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 4da9292..42c43aa 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -11,6 +11,7 @@ from sqlalchemy.dialects import postgresql as psql from sqlalchemy.ext import hybrid as sa_hybrid from velofy import config as pkg_config +from velofy import db from velofy.db import meta from velofy.db import utils @@ -104,19 +105,28 @@ class Address(meta.Base): ) # Relationships - city = orm.relationship("City", back_populates="addresses") - restaurants = orm.relationship("Restaurant", back_populates="address") - orders_picked_up = orm.relationship( + city: orm.Mapped["db.City"] = orm.relationship( + "City", + back_populates="addresses", + ) + restaurants: orm.Mapped[list["db.Restaurant"]] = orm.relationship( + "Restaurant", + back_populates="address", + ) + orders_picked_up: orm.Mapped[list["db.Order"]] = orm.relationship( "Order", back_populates="pickup_address", foreign_keys="[Order.pickup_address_id]", ) - orders_delivered = orm.relationship( + orders_delivered: orm.Mapped[list["db.Order"]] = orm.relationship( "Order", back_populates="delivery_address", foreign_keys="[Order.delivery_address_id]", ) - pixels = orm.relationship("AddressPixelAssociation", back_populates="address") + pixels: orm.Mapped[list["db.AddressPixelAssociation"]] = orm.relationship( + "AddressPixelAssociation", + back_populates="address", + ) def __repr__(self) -> str: """Non-literal text representation.""" -- 2.47.3 From de86c2e64d37a0bfcdb7e392df3409c781a03924 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:12:50 +0100 Subject: [PATCH 07/32] Type the relationships of `AddressPixelAssociation` --- src/velofy/db/addresses_pixels.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/velofy/db/addresses_pixels.py b/src/velofy/db/addresses_pixels.py index 60133a5..3fd5ed2 100644 --- a/src/velofy/db/addresses_pixels.py +++ b/src/velofy/db/addresses_pixels.py @@ -3,6 +3,7 @@ import sqlalchemy as sa from sqlalchemy import orm +from velofy import db from velofy.db import meta @@ -64,5 +65,11 @@ class AddressPixelAssociation(meta.Base): ) # Relationships - address = orm.relationship("Address", back_populates="pixels") - pixel = orm.relationship("Pixel", back_populates="addresses") + address: orm.Mapped[db.Address] = orm.relationship( + "Address", + back_populates="pixels", + ) + pixel: orm.Mapped["db.Pixel"] = orm.relationship( + "Pixel", + back_populates="addresses", + ) -- 2.47.3 From 8f5d11db7f4abccb06b47fe6e0cc3ceaa2a87db7 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:13:03 +0100 Subject: [PATCH 08/32] Type the relationships of `City` --- src/velofy/db/cities.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 2c2bcb7..e232953 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -64,9 +64,18 @@ class City(meta.Base): ) # Relationships - addresses = orm.relationship("Address", back_populates="city") - grids = orm.relationship("Grid", back_populates="city") - replays = orm.relationship("ReplaySimulation", back_populates="city") + addresses: orm.Mapped[list[db.Address]] = orm.relationship( + "Address", + back_populates="city", + ) + grids: orm.Mapped[list["db.Grid"]] = orm.relationship( + "Grid", + back_populates="city", + ) + replays: orm.Mapped[list["db.ReplaySimulation"]] = orm.relationship( + "ReplaySimulation", + back_populates="city", + ) # We do not implement a `.__init__()` method and use SQLAlchemy's default. # The uninitialized attribute `._map` is computed on the fly. note:d334120ei -- 2.47.3 From 99c8c2ac2e010797d07c887b8a5ffbbe8afc3568 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:13:15 +0100 Subject: [PATCH 09/32] Type the relationships of `Courier` --- src/velofy/db/couriers.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/velofy/db/couriers.py b/src/velofy/db/couriers.py index 2c3aeb9..03b1623 100644 --- a/src/velofy/db/couriers.py +++ b/src/velofy/db/couriers.py @@ -6,6 +6,7 @@ import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql +from velofy import db from velofy.db import meta @@ -68,7 +69,10 @@ class Courier(meta.Base): ) # Relationships - orders = orm.relationship("Order", back_populates="courier") + orders: orm.Mapped[list["db.Order"]] = orm.relationship( + "Order", + back_populates="courier", + ) def __repr__(self) -> str: """Non-literal text representation.""" -- 2.47.3 From bda9cf69edc8a6d5db3784a092251eeb90519768 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:13:27 +0100 Subject: [PATCH 10/32] Type the relationships of `Customer` --- src/velofy/db/customers.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 25bbc35..5c852ae 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -26,7 +26,10 @@ class Customer(meta.Base): return f"<{self.__class__.__name__}(#{self.id})>" # Relationships - orders = orm.relationship("Order", back_populates="customer") + orders: orm.Mapped[list["db.Order"]] = orm.relationship( + "Order", + back_populates="customer", + ) def clear_map(self) -> "Customer": # pragma: no cover """Shortcut to the `...city.clear_map()` method. -- 2.47.3 From 90c05971936f052130da278cda151c44fb39bd63 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:13:40 +0100 Subject: [PATCH 11/32] Type the relationships of `Forecast` Also, move the `db` import to the top --- src/velofy/db/forecasts.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index c2b24f0..877f6fa 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -8,6 +8,7 @@ import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql +from velofy import db from velofy.db import meta @@ -174,7 +175,10 @@ class Forecast(meta.Base): ) # Relationships - pixel = orm.relationship("Pixel", back_populates="forecasts") + pixel: orm.Mapped["db.Pixel"] = orm.relationship( + "Pixel", + back_populates="forecasts", + ) def __repr__(self) -> str: """Non-literal text representation.""" @@ -255,6 +259,3 @@ class Forecast(meta.Base): ) return forecasts - - -from velofy import db # noqa:E402 isort:skip -- 2.47.3 From 9a2ec3d86b37d7f854ed19bd95ed33bfd8409fd1 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 10:05:14 +0100 Subject: [PATCH 12/32] Type the relationships of `Grid` --- src/velofy/db/grids.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index 1c97748..e307e96 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -51,8 +51,14 @@ class Grid(meta.Base): ) # Relationships - city = orm.relationship("City", back_populates="grids") - pixels = orm.relationship("Pixel", back_populates="grid") + city: orm.Mapped[db.City] = orm.relationship( + "City", + back_populates="grids", + ) + pixels: orm.Mapped[list["db.Pixel"]] = orm.relationship( + "Pixel", + back_populates="grid", + ) def __repr__(self) -> str: """Non-literal text representation.""" -- 2.47.3 From f45a444f8365aeaad3212be7bd3b65b1222bd89c Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:13:52 +0100 Subject: [PATCH 13/32] Type the relationships of `Order` --- src/velofy/db/orders.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/velofy/db/orders.py b/src/velofy/db/orders.py index 00b6cba..4aaa6bf 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -493,24 +493,33 @@ class Order(meta.Base): ) # Relationships - customer = orm.relationship("Customer", back_populates="orders") - restaurant = orm.relationship( + customer: orm.Mapped[db.Customer] = orm.relationship( + "Customer", + back_populates="orders", + ) + restaurant: orm.Mapped["db.Restaurant"] = orm.relationship( "Restaurant", back_populates="orders", primaryjoin="Restaurant.id == Order.restaurant_id", ) - courier = orm.relationship("Courier", back_populates="orders") - pickup_address = orm.relationship( + courier: orm.Mapped[db.Courier | None] = orm.relationship( + "Courier", + back_populates="orders", + ) + pickup_address: orm.Mapped[db.Address] = orm.relationship( "Address", back_populates="orders_picked_up", foreign_keys="[Order.pickup_address_id]", ) - delivery_address = orm.relationship( + delivery_address: orm.Mapped[db.Address] = orm.relationship( "Address", back_populates="orders_delivered", foreign_keys="[Order.delivery_address_id]", ) - replays = orm.relationship("ReplayedOrder", back_populates="actual") + replays: orm.Mapped[list["db.ReplayedOrder"]] = orm.relationship( + "ReplayedOrder", + back_populates="actual", + ) # Convenience properties -- 2.47.3 From af0e3cf1a17a031e03381b8c06bf02b92a35265a Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:12:38 +0100 Subject: [PATCH 14/32] Type the relationships of `Path` --- src/velofy/db/addresses_addresses.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 892ef4c..16a50aa 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -109,11 +109,11 @@ class Path(meta.Base): ) # Relationships - first_address = orm.relationship( + first_address: orm.Mapped[db.Address] = orm.relationship( "Address", foreign_keys="[Path.first_address_id, Path.city_id]", ) - second_address = orm.relationship( + second_address: orm.Mapped[db.Address] = orm.relationship( "Address", foreign_keys="[Path.second_address_id, Path.city_id]", overlaps="first_address", -- 2.47.3 From 699e7f0443cdb986f62e6752ade11656feeedd94 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:14:04 +0100 Subject: [PATCH 15/32] Type the relationships of `Pixel` --- src/velofy/db/pixels.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 9df0314..2614719 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -63,9 +63,18 @@ class Pixel(meta.Base): ) # Relationships - grid = orm.relationship("Grid", back_populates="pixels") - addresses = orm.relationship("AddressPixelAssociation", back_populates="pixel") - forecasts = orm.relationship("Forecast", back_populates="pixel") + grid: orm.Mapped[db.Grid] = orm.relationship( + "Grid", + back_populates="pixels", + ) + addresses: orm.Mapped[list[db.AddressPixelAssociation]] = orm.relationship( + "AddressPixelAssociation", + back_populates="pixel", + ) + forecasts: orm.Mapped[list[db.Forecast]] = orm.relationship( + "Forecast", + back_populates="pixel", + ) def __repr__(self) -> str: """Non-literal text representation.""" -- 2.47.3 From 4be6078327dadd1395454c0901a333441f1023b8 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:14:29 +0100 Subject: [PATCH 16/32] Type the relationships of `ReplayedOrder` Also, move the `db` import to the top, which makes some quotes unnecessary --- src/velofy/db/replay/orders.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index 0d990b7..b59d706 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -5,6 +5,7 @@ import datetime as dt import sqlalchemy as sa from sqlalchemy import orm +from velofy import db from velofy.db import meta @@ -396,9 +397,17 @@ class ReplayedOrder(meta.Base): ) # Relationships - simulation = orm.relationship("ReplaySimulation", back_populates="orders") - actual = orm.relationship("Order", back_populates="replays") - courier = orm.relationship("Courier") + simulation: orm.Mapped["db.ReplaySimulation"] = orm.relationship( + "ReplaySimulation", + back_populates="orders", + ) + actual: orm.Mapped[db.Order] = orm.relationship( + "Order", + back_populates="replays", + ) + courier: orm.Mapped[db.Courier | None] = orm.relationship( + "Courier", + ) def __repr__(self) -> str: """Non-literal text representation.""" @@ -407,7 +416,7 @@ class ReplayedOrder(meta.Base): # Convenience properties @property - def customer(self) -> "db.Customer": + def customer(self) -> db.Customer: """`.customer` of the actual `Order`.""" return self.actual.customer @@ -417,14 +426,11 @@ class ReplayedOrder(meta.Base): return self.actual.restaurant @property - def pickup_address(self) -> "db.Address": + def pickup_address(self) -> db.Address: """`.pickup_address` of the actual `Order`.""" return self.actual.pickup_address @property - def delivery_address(self) -> "db.Address": + def delivery_address(self) -> db.Address: """`.delivery_address` of the actual `Order`.""" return self.actual.delivery_address - - -from velofy import db # noqa:E402 isort:skip -- 2.47.3 From 5ad3fb538de52bac61b3ffc901303e986ae591f0 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:18:30 +0100 Subject: [PATCH 17/32] Type the relationships of `ReplaySimulation` --- src/velofy/db/replay/simulations.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/velofy/db/replay/simulations.py b/src/velofy/db/replay/simulations.py index f6bb815..883e8a6 100644 --- a/src/velofy/db/replay/simulations.py +++ b/src/velofy/db/replay/simulations.py @@ -3,6 +3,7 @@ import sqlalchemy as sa from sqlalchemy import orm +from velofy import db from velofy.db import meta @@ -50,8 +51,14 @@ class ReplaySimulation(meta.Base): ) # Relationships - city = orm.relationship("City", back_populates="replays") - orders = orm.relationship("ReplayedOrder", back_populates="simulation") + city: orm.Mapped[db.City] = orm.relationship( + "City", + back_populates="replays", + ) + orders: orm.Mapped[list["db.ReplayedOrder"]] = orm.relationship( + "ReplayedOrder", + back_populates="simulation", + ) def __repr__(self) -> str: """Non-literal text representation.""" -- 2.47.3 From 76982126f43fc07ca690e10e933097bba7cd1755 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:14:17 +0100 Subject: [PATCH 18/32] Type the relationships of `Restaurant` --- src/velofy/db/restaurants.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 733006d..5f7acbc 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -62,8 +62,11 @@ class Restaurant(meta.Base): ) # Relationships - address = orm.relationship("Address", back_populates="restaurants") - orders = orm.relationship( + address: orm.Mapped[db.Address] = orm.relationship( + "Address", + back_populates="restaurants", + ) + orders: orm.Mapped[list[db.Order]] = orm.relationship( "Order", back_populates="restaurant", overlaps="orders_picked_up,pickup_address", -- 2.47.3 From 0d2aab42116c050145e54c563b4f0a876db69e2a Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:02:12 +0100 Subject: [PATCH 19/32] Use `t.Self` for methods returning their own class --- src/velofy/db/addresses.py | 2 +- src/velofy/db/addresses_addresses.py | 11 ++++++----- src/velofy/db/cities.py | 3 ++- src/velofy/db/customers.py | 4 +++- src/velofy/db/forecasts.py | 3 ++- src/velofy/db/grids.py | 4 ++-- src/velofy/db/pixels.py | 3 ++- src/velofy/db/restaurants.py | 3 ++- 8 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 42c43aa..2ba8588 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -179,7 +179,7 @@ class Address(meta.Base): """ return self.location.y - def clear_map(self) -> "Address": # pragma: no cover + def clear_map(self) -> t.Self: # pragma: no cover """Shortcut to the `.city.clear_map()` method. Returns: diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 16a50aa..af14092 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -3,6 +3,7 @@ import functools import itertools import json +import typing as t import folium import googlemaps as gm @@ -124,7 +125,7 @@ class Path(meta.Base): cls, *addresses: db.Address, google_maps: bool = False, - ) -> list["Path"]: + ) -> list[t.Self]: """Calculate pair-wise paths for `Address` objects. This is the main constructor method for the class. @@ -151,9 +152,9 @@ class Path(meta.Base): # If there is no `Path` object in the database ... path = ( - db.session.query(db.Path) - .filter(db.Path.first_address == first) - .filter(db.Path.second_address == second) + db.session.query(cls) + .filter(cls.first_address == first) + .filter(cls.second_address == second) .first() ) # ... create a new one. @@ -181,7 +182,7 @@ class Path(meta.Base): return paths @classmethod - def from_order(cls, order: "db.Order", *, google_maps: bool = False) -> "Path": + def from_order(cls, order: "db.Order", *, google_maps: bool = False) -> t.Self: """Calculate the path for an `Order` object. The path goes from the `Order.pickup_address` to the `Order.delivery_address`. diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index e232953..570baa6 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -1,6 +1,7 @@ """Provide the ORM's `City` model.""" import functools +import typing as t import folium import sqlalchemy as sa @@ -127,7 +128,7 @@ class City(meta.Base): """ return self.northeast.northing - self.southwest.northing - def clear_map(self) -> "City": # pragma: no cover + def clear_map(self) -> t.Self: # pragma: no cover """Create a new `folium.Map` object aligned with the city's viewport. The map is available via the `.map` property. Note that it is mutable diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 5c852ae..7a9e4b1 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -1,5 +1,7 @@ """Provide the ORM's `Customer` model.""" +import typing as t + import folium import sqlalchemy as sa from sqlalchemy import orm @@ -31,7 +33,7 @@ class Customer(meta.Base): back_populates="customer", ) - def clear_map(self) -> "Customer": # pragma: no cover + def clear_map(self) -> t.Self: # pragma: no cover """Shortcut to the `...city.clear_map()` method. Returns: diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 877f6fa..0f04a45 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -2,6 +2,7 @@ import datetime as dt import math +import typing as t import pandas as pd import sqlalchemy as sa @@ -194,7 +195,7 @@ class Forecast(meta.Base): train_horizon: int, model: str, data: pd.DataFrame, - ) -> list["db.Forecast"]: + ) -> list[t.Self]: """Convert results from the forecasting `*Model`s into `Forecast` objects. This is an alternative constructor method. diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index e307e96..365f7c0 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -71,7 +71,7 @@ class Grid(meta.Base): return round((self.side_length**2) / 1_000_000, 1) @classmethod - def gridify(cls, city: db.City, side_length: int) -> "db.Grid": + def gridify(cls, city: db.City, side_length: int) -> t.Self: """Create a fully populated `Grid` for a `city`. The `Grid` contains only `Pixel`s that have at least one @@ -126,7 +126,7 @@ class Grid(meta.Base): return grid - def clear_map(self) -> "Grid": # pragma: no cover + def clear_map(self) -> t.Self: # pragma: no cover """Shortcut to the `.city.clear_map()` method. Returns: diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 2614719..001ef3c 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -1,6 +1,7 @@ """Provide the ORM's `Pixel` model.""" import functools +import typing as t import folium import sqlalchemy as sa @@ -149,7 +150,7 @@ class Pixel(meta.Base): .all() ) - def clear_map(self) -> "Pixel": # pragma: no cover + def clear_map(self) -> t.Self: # pragma: no cover """Shortcut to the `.city.clear_map()` method. Returns: diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 5f7acbc..7936b60 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -1,6 +1,7 @@ """Provide the ORM's `Restaurant` model.""" import datetime as dt +import typing as t import folium import sqlalchemy as sa @@ -76,7 +77,7 @@ class Restaurant(meta.Base): """Non-literal text representation.""" return f"<{self.__class__.__name__}({self.name})>" - def clear_map(self) -> "Restaurant": # pragma: no cover + def clear_map(self) -> t.Self: # pragma: no cover """Shortcut to the `.address.city.clear_map()` method. Returns: -- 2.47.3 From bbc00e2f1cd3dc17599eed50a82dc6258541c863 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 12:35:24 +0100 Subject: [PATCH 20/32] Enable "disallow_any_unimported" --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index f45a128..4a8160d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -446,6 +446,9 @@ check_untyped_defs = true # Disallow generic types without explicit type parameters disallow_any_generics = true +# Disallow types that become `Any` because their library is untyped +disallow_any_unimported = true + # Disallow functions with incomplete type annotations disallow_incomplete_defs = true -- 2.47.3 From 0a5f8f6c5575f87a2c2be292bcc292b606386c47 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 11:42:34 +0100 Subject: [PATCH 21/32] Enable "warn_return_any" --- pyproject.toml | 4 ++-- src/velofy/forecasts/methods/arima.py | 2 +- src/velofy/forecasts/methods/ets.py | 2 +- src/velofy/forecasts/timify.py | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4a8160d..6f7ab42 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -483,8 +483,8 @@ strict_equality = true # Report `t.cast()` calls that are not needed warn_redundant_casts = true -# Allow returning `Any` as long as the ORM models' relationships are untyped -warn_return_any = false +# Report functions returning `Any` despite a non-`Any` return type +warn_return_any = true # Report "[[tool.mypy.overrides]]" sections that match no module warn_unused_configs = true diff --git a/src/velofy/forecasts/methods/arima.py b/src/velofy/forecasts/methods/arima.py index 9391063..7c09898 100644 --- a/src/velofy/forecasts/methods/arima.py +++ b/src/velofy/forecasts/methods/arima.py @@ -64,7 +64,7 @@ def predict( ) # Convert the results into a nice `pd.DataFrame` with the right `.index`. - forecasts = pandas2ri.rpy2py(result) + forecasts: pd.DataFrame = pandas2ri.rpy2py(result) forecasts.index = forecast_interval return forecasts.round(5).rename( diff --git a/src/velofy/forecasts/methods/ets.py b/src/velofy/forecasts/methods/ets.py index 58a11ad..d9691ff 100644 --- a/src/velofy/forecasts/methods/ets.py +++ b/src/velofy/forecasts/methods/ets.py @@ -65,7 +65,7 @@ def predict( ) # Convert the results into a nice `pd.DataFrame` with the right `.index`. - forecasts = pandas2ri.rpy2py(result) + forecasts: pd.DataFrame = pandas2ri.rpy2py(result) forecasts.index = forecast_interval return forecasts.round(5).rename( diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 43119ed..bb9ab81 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -555,9 +555,9 @@ class OrderHistory: first_day = training_ts.index.min().date() last_day = training_ts.index.max().date() # `+1` as both `first_day` and `last_day` are included. - n_days = (last_day - first_day).days + 1 + n_days: int = (last_day - first_day).days + 1 - return round(training_ts.sum() / n_days, 1) + return round(float(training_ts.sum()) / n_days, 1) def choose_tactical_model( self, -- 2.47.3 From 784d5c8ca04eb7c9419294703e80de8227c1a21b Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:02:57 +0100 Subject: [PATCH 22/32] Enable "warn_unreachable" Also, remove the dead `isinstance()` check in `Location.relate_to()` --- pyproject.toml | 3 +++ src/velofy/db/utils/locations.py | 4 ---- tests/db/utils/test_locations.py | 5 ----- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6f7ab42..6a4752d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -486,6 +486,9 @@ warn_redundant_casts = true # Report functions returning `Any` despite a non-`Any` return type warn_return_any = true +# Report code that can never be reached +warn_unreachable = true + # Report "[[tool.mypy.overrides]]" sections that match no module warn_unused_configs = true diff --git a/src/velofy/db/utils/locations.py b/src/velofy/db/utils/locations.py index e5ba650..8b95cba 100644 --- a/src/velofy/db/utils/locations.py +++ b/src/velofy/db/utils/locations.py @@ -144,10 +144,6 @@ class Location: msg = "the `other` origin may only be set once" raise RuntimeError(msg) - if not isinstance(other, Location): - msg = "`other` is not a `Location` object" - raise TypeError(msg) - if self.zone != other.zone: msg = "`other` must be in the same zone, including the band" raise ValueError(msg) diff --git a/tests/db/utils/test_locations.py b/tests/db/utils/test_locations.py index 8257652..ff9eefc 100644 --- a/tests/db/utils/test_locations.py +++ b/tests/db/utils/test_locations.py @@ -169,11 +169,6 @@ class TestRelateTo: with pytest.raises(RuntimeError, match="once"): location.relate_to(origin) - def test_call_relate_to_with_wrong_other_type(self, location): - """`other` must be another `Location`.""" - with pytest.raises(TypeError, match="Location"): - location.relate_to(object()) - def test_call_relate_to_with_far_away_other( self, location, -- 2.47.3 From a4c157413552732941d45d9af03f6100aa274815 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:11:30 +0100 Subject: [PATCH 23/32] Enable the "deprecated" error code --- pyproject.toml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6a4752d..3d8040f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -468,8 +468,13 @@ disallow_untyped_decorators = true # Disallow functions without type annotations (or incomplete annotations) disallow_untyped_defs = true -# Require an error code in all "# type: ignore" comments -enable_error_code = ["ignore-without-code"] +# Enable error codes that are off by default +enable_error_code = [ + # Report usages of APIs marked with `@deprecated` + "deprecated", + # Require an error code in all "# type: ignore" comments + "ignore-without-code", +] # Check further edge cases that are rarely an issue in practice extra_checks = true -- 2.47.3 From dafc6956937849133a8b9106bec51c94eb6a7c23 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:11:31 +0100 Subject: [PATCH 24/32] Enable the "mutable-override" error code --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 3d8040f..9643082 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -474,6 +474,8 @@ enable_error_code = [ "deprecated", # Require an error code in all "# type: ignore" comments "ignore-without-code", + # Report overrides of mutable attributes with incompatible types + "mutable-override", ] # Check further edge cases that are rarely an issue in practice -- 2.47.3 From 719072426094618a32fc0c42e6bcea133e45ad1f Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:11:32 +0100 Subject: [PATCH 25/32] Enable the "possibly-undefined" error code --- pyproject.toml | 2 ++ src/velofy/console/gridify.py | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 9643082..0d943dd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -476,6 +476,8 @@ enable_error_code = [ "ignore-without-code", # Report overrides of mutable attributes with incompatible types "mutable-override", + # Report variables that may be used before they are assigned + "possibly-undefined", ] # Check further edge cases that are rarely an issue in practice diff --git a/src/velofy/console/gridify.py b/src/velofy/console/gridify.py index 9cc0591..9da5e5d 100644 --- a/src/velofy/console/gridify.py +++ b/src/velofy/console/gridify.py @@ -36,9 +36,10 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 # Because the number of assigned addresses is the same across # different `side_length`s, we can take the last `grid` from the `city`. + last_grid_id = grid.id # type: ignore[possibly-undefined] n_assigned = ( db.session.query(db.AddressPixelAssociation) - .filter(db.AddressPixelAssociation.grid_id == grid.id) + .filter(db.AddressPixelAssociation.grid_id == last_grid_id) .count() ) click.echo( -- 2.47.3 From fef268321a9cf0924fc4facb33b4002046e7fd36 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:11:45 +0100 Subject: [PATCH 26/32] Enable the "redundant-expr" error code --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 0d943dd..0373cb1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -478,6 +478,8 @@ enable_error_code = [ "mutable-override", # Report variables that may be used before they are assigned "possibly-undefined", + # Report conditions that are always true or always false + "redundant-expr", ] # Check further edge cases that are rarely an issue in practice -- 2.47.3 From 9da2d0b70363911386c5fa4ecf57ecda55b15a86 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:11:46 +0100 Subject: [PATCH 27/32] Enable the "truthy-bool" error code --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 0373cb1..d8f4be7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -480,6 +480,8 @@ enable_error_code = [ "possibly-undefined", # Report conditions that are always true or always false "redundant-expr", + # Report truthiness checks on objects that are always true + "truthy-bool", ] # Check further edge cases that are rarely an issue in practice -- 2.47.3 From 883a3ab8cc00ce1dce317d6da5a73571a437d620 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:11:47 +0100 Subject: [PATCH 28/32] Enable the "truthy-iterable" error code --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index d8f4be7..4ec7d10 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -482,6 +482,8 @@ enable_error_code = [ "redundant-expr", # Report truthiness checks on objects that are always true "truthy-bool", + # Report truthiness checks on `Iterable`s that are always true + "truthy-iterable", ] # Check further edge cases that are rarely an issue in practice -- 2.47.3 From 369957c06b5ddd8170345c0522af5f1259fc26d6 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:37:49 +0100 Subject: [PATCH 29/32] Narrow the untyped calls of `folium.PolyLine` --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 4ec7d10..fb580cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -459,7 +459,7 @@ disallow_subclassing_any = true disallow_untyped_calls = true # ... except for libraries without type annotations untyped_calls_exclude = [ - "folium", + "folium.vector_layers", ] # Disallow decorators without type annotations -- 2.47.3 From f7a6aa1881753ae42915fccaba4511b01decade6 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:54:23 +0100 Subject: [PATCH 30/32] Type-check `noxfile.py` --- noxfile.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/noxfile.py b/noxfile.py index eb69d5f..8b6d9df 100644 --- a/noxfile.py +++ b/noxfile.py @@ -63,7 +63,10 @@ def load_pyproject_toml() -> collections.defaultdict[str, t.Any]: so, missing keys and tables (i.e., "sections" in the .ini format) do not result in `KeyError`s but return empty `nested_defaultdict`s. """ - return defaultify(nox.project.load_toml("pyproject.toml")) + return t.cast( + collections.defaultdict[str, t.Any], + defaultify(nox.project.load_toml("pyproject.toml")), + ) def load_supported_python_versions(*, reverse: bool = False) -> list[str]: @@ -77,6 +80,9 @@ def load_supported_python_versions(*, reverse: bool = False) -> list[str]: return sorted(version_names, key=pkg_version.Version, reverse=reverse) +# The "./" keeps `bandit` from warning about its module name +NOXFILE_LOCATION = "./noxfile.py" + PACKAGE = "velofy" PACKAGE_LOCATION = "src/" @@ -90,7 +96,7 @@ SRC_LOCATIONS = ( f"{DOCS_LOCATION}conf.py", "migrations/env.py", "migrations/versions/", - "./noxfile.py", # The "./" keeps `bandit` from warning about its module name + NOXFILE_LOCATION, "scripts/", PACKAGE_LOCATION, TESTS_LOCATION, @@ -180,7 +186,7 @@ def lint_code(session: nox.Session) -> None: If no extra arguments are provided, all source files are linted. Otherwise, they are interpreted as paths the linters work on recursively. - `mypy` always checks the entire package regardless + `mypy` always checks the noxfile and the entire package regardless because it needs the whole program to follow types across modules. """ start(session) @@ -220,6 +226,7 @@ def lint_code(session: nox.Session) -> None: "flake8-unused-arguments", "isort", "mypy", + "nox", # Because we type-check the noxfile.py as well "pandas-stubs", "pandas-vet", "pep8-naming", @@ -243,7 +250,7 @@ def lint_code(session: nox.Session) -> None: session.run("ruff", "check", *locations) session.run("mypy", "--version") - session.run("mypy", PACKAGE_LOCATION) + session.run("mypy", NOXFILE_LOCATION, PACKAGE_LOCATION) @nox.session(name="test", python=MAIN_PYTHON) @@ -567,7 +574,7 @@ def do_not_accept_arguments(session: nox.Session, *, raise_error: bool = True) - def do_not_reuse(session: nox.Session, *, raise_error: bool = True) -> None: """Do not reuse a session with the "-r" or "-R" flags.""" - if session._runner.venv._reused: # noqa:SLF001 + if session.virtualenv._reused: # noqa:SLF001 msg = 'be run without the "-r" and "-R" flags' if raise_error: @@ -656,7 +663,7 @@ def skip_install(session: nox.Session) -> bool: # Same logic to skip package installation as in core `nox` # See: https://github.com/wntrblm/nox/blob/2026.10.20/nox/sessions.py#L905 no_install = session._runner.global_config.no_install # noqa:SLF001 - venv_reused = session._runner.venv._reused # noqa:SLF001 + venv_reused = session.virtualenv._reused # noqa:SLF001 return bool(no_install and venv_reused) -- 2.47.3 From d6b798a736992289b01e8e6d2b86b3947504f57d Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 13:57:42 +0100 Subject: [PATCH 31/32] Type-check `scripts/` --- noxfile.py | 8 +++++--- scripts/get_update_info_for_dependencies.py | 7 ++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/noxfile.py b/noxfile.py index 8b6d9df..1abc577 100644 --- a/noxfile.py +++ b/noxfile.py @@ -89,6 +89,8 @@ PACKAGE_LOCATION = "src/" DOCS_BUILD = ".cache/docs/" DOCS_LOCATION = "docs/" +SCRIPTS_LOCATION = "scripts/" + TESTS_LOCATION = "tests/" # Locations of all *.py files @@ -97,7 +99,7 @@ SRC_LOCATIONS = ( "migrations/env.py", "migrations/versions/", NOXFILE_LOCATION, - "scripts/", + SCRIPTS_LOCATION, PACKAGE_LOCATION, TESTS_LOCATION, ) @@ -186,7 +188,7 @@ def lint_code(session: nox.Session) -> None: If no extra arguments are provided, all source files are linted. Otherwise, they are interpreted as paths the linters work on recursively. - `mypy` always checks the noxfile and the entire package regardless + `mypy` always checks the noxfile, the scripts, and the package regardless because it needs the whole program to follow types across modules. """ start(session) @@ -250,7 +252,7 @@ def lint_code(session: nox.Session) -> None: session.run("ruff", "check", *locations) session.run("mypy", "--version") - session.run("mypy", NOXFILE_LOCATION, PACKAGE_LOCATION) + session.run("mypy", NOXFILE_LOCATION, SCRIPTS_LOCATION, PACKAGE_LOCATION) @nox.session(name="test", python=MAIN_PYTHON) diff --git a/scripts/get_update_info_for_dependencies.py b/scripts/get_update_info_for_dependencies.py index 9ca926e..4100244 100755 --- a/scripts/get_update_info_for_dependencies.py +++ b/scripts/get_update_info_for_dependencies.py @@ -14,6 +14,7 @@ import json import pathlib import textwrap import tomllib +import typing as t PKG_CONSIDERED_OLD = 2 # years after release when a package is considered "old" @@ -23,7 +24,7 @@ PROJECT_ROOT = pathlib.Path(__file__).resolve().parent.parent REPORT_FILE = PROJECT_ROOT / ".cache/dependencies_checked.txt" -def get_direct_dependencies(lock_file: dict) -> dict[str, str]: +def get_direct_dependencies(lock_file: dict[str, t.Any]) -> dict[str, str]: """Map the direct dependencies to "main" or their extra or group. `lock_file` is a mapping as returned from `load_lock_file()`. @@ -41,7 +42,7 @@ def get_direct_dependencies(lock_file: dict) -> dict[str, str]: return labels -def get_pinned_packages(lock_file: dict) -> dict[str, str]: +def get_pinned_packages(lock_file: dict[str, t.Any]) -> dict[str, str]: """Map all packages from PyPI to their versions. `lock_file` is a mapping as returned from `load_lock_file()`. @@ -84,7 +85,7 @@ def get_years_since_release( return round(years_since_release, 1), latest_version -def load_lock_file() -> dict: +def load_lock_file() -> dict[str, t.Any]: """Load the uv.lock file.""" return tomllib.loads((PROJECT_ROOT / "uv.lock").read_text()) -- 2.47.3 From 081d6f7fd9b32ab5c4f27505612cb96e68ed16e5 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 14:23:14 +0100 Subject: [PATCH 32/32] Type the time series of `OrderHistory` as `pd.Series[int]` --- src/velofy/forecasts/timify.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index bb9ab81..cc49669 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -255,7 +255,7 @@ class OrderHistory: pixel_id: int, predict_at: dt.datetime, train_horizon: int, - ) -> tuple[pd.Series, int, pd.Series]: + ) -> tuple["pd.Series[int]", int, "pd.Series[int]"]: """Slice a horizontal time series out of the `.totals`. Create a time series covering `train_horizon` weeks that can be used @@ -331,7 +331,7 @@ class OrderHistory: pixel_id: int, predict_day: dt.date, train_horizon: int, - ) -> tuple[pd.Series, int, pd.Series]: + ) -> tuple["pd.Series[int]", int, "pd.Series[int]"]: """Slice a vertical time series out of the `.totals`. Create a time series covering `train_horizon` weeks that can be used @@ -424,7 +424,7 @@ class OrderHistory: pixel_id: int, predict_at: dt.datetime, train_horizon: int, - ) -> tuple[pd.Series, int, pd.Series]: + ) -> tuple["pd.Series[int]", int, "pd.Series[int]"]: """Slice a vertical real-time time series out of the `.totals`. Create a time series covering `train_horizon` weeks that can be used @@ -557,7 +557,7 @@ class OrderHistory: # `+1` as both `first_day` and `last_day` are included. n_days: int = (last_day - first_day).days + 1 - return round(float(training_ts.sum()) / n_days, 1) + return round(training_ts.sum() / n_days, 1) def choose_tactical_model( self, -- 2.47.3