diff --git a/noxfile.py b/noxfile.py index eb69d5f..1abc577 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,12 +80,17 @@ 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/" DOCS_BUILD = ".cache/docs/" DOCS_LOCATION = "docs/" +SCRIPTS_LOCATION = "scripts/" + TESTS_LOCATION = "tests/" # Locations of all *.py files @@ -90,8 +98,8 @@ SRC_LOCATIONS = ( f"{DOCS_LOCATION}conf.py", "migrations/env.py", "migrations/versions/", - "./noxfile.py", # The "./" keeps `bandit` from warning about its module name - "scripts/", + NOXFILE_LOCATION, + SCRIPTS_LOCATION, PACKAGE_LOCATION, TESTS_LOCATION, ) @@ -180,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 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) @@ -220,6 +228,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 +252,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, SCRIPTS_LOCATION, PACKAGE_LOCATION) @nox.session(name="test", python=MAIN_PYTHON) @@ -567,7 +576,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 +665,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) diff --git a/pyproject.toml b/pyproject.toml index cc4d0e5..fb580cc 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 @@ -444,21 +446,66 @@ 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 +# Disallow subclassing classes typed `Any` +disallow_subclassing_any = true + # Disallow calling functions without type annotations ... disallow_untyped_calls = true # ... except for libraries without type annotations untyped_calls_exclude = [ - "folium", + "folium.vector_layers", ] +# 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"] +# 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", + # Report overrides of mutable attributes with incompatible types + "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", + # 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 +extra_checks = true + +# 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 + +# Report `t.cast()` calls that are not needed +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 # Report "# type: ignore" comments that are not needed anymore warn_unused_ignores = true @@ -622,6 +669,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 @@ -725,7 +774,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/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()) 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/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( 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/addresses.py b/src/velofy/db/addresses.py index 0c16f2c..2ba8588 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 @@ -13,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 @@ -106,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.""" @@ -171,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 9defe93..af14092 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -1,10 +1,9 @@ """Model for the `Path` relationship between two `Address` objects.""" -from __future__ import annotations - import functools import itertools import json +import typing as t import folium import googlemaps as gm @@ -111,11 +110,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", @@ -126,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. @@ -153,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. @@ -183,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/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", + ) diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index a6fc363..570baa6 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -1,8 +1,7 @@ """Provide the ORM's `City` model.""" -from __future__ import annotations - import functools +import typing as t import folium import sqlalchemy as sa @@ -66,9 +65,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 @@ -120,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/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.""" diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index b7b146c..7a9e4b1 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -1,6 +1,6 @@ """Provide the ORM's `Customer` model.""" -from __future__ import annotations +import typing as t import folium import sqlalchemy as sa @@ -28,9 +28,12 @@ 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 + 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 1733394..0f04a45 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -1,15 +1,15 @@ """Provide the ORM's `Forecast` model.""" -from __future__ import annotations - import datetime as dt import math +import typing as t import pandas as pd import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql +from velofy import db from velofy.db import meta @@ -176,7 +176,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.""" @@ -187,12 +190,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[t.Self]: """Convert results from the forecasting `*Model`s into `Forecast` objects. This is an alternative constructor method. @@ -257,6 +260,3 @@ class Forecast(meta.Base): ) return forecasts - - -from velofy import db # noqa:E402 isort:skip diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index ec8802e..365f7c0 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 @@ -53,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.""" @@ -67,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 @@ -122,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/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", }, - ), -) + ) 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 diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 61c5ecf..001ef3c 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -1,8 +1,7 @@ """Provide the ORM's `Pixel` model.""" -from __future__ import annotations - import functools +import typing as t import folium import sqlalchemy as sa @@ -65,9 +64,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.""" @@ -130,7 +138,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 +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/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/replay/orders.py b/src/velofy/db/replay/orders.py index 4e32ceb..b59d706 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -1,12 +1,11 @@ """Provide the ORM's `ReplayedOrder` model for the replay simulations.""" -from __future__ import annotations - import datetime as dt import sqlalchemy as sa from sqlalchemy import orm +from velofy import db from velofy.db import meta @@ -398,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.""" @@ -414,7 +421,7 @@ class ReplayedOrder(meta.Base): return self.actual.customer @property - def restaurant(self) -> db.Restaurant: + def restaurant(self) -> "db.Restaurant": """`.restaurant` of the actual `Order`.""" return self.actual.restaurant @@ -427,6 +434,3 @@ class ReplayedOrder(meta.Base): 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 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.""" diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 73bb101..7936b60 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -1,8 +1,7 @@ """Provide the ORM's `Restaurant` model.""" -from __future__ import annotations - import datetime as dt +import typing as t import folium import sqlalchemy as sa @@ -64,8 +63,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", @@ -75,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: 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/db/utils/locations.py b/src/velofy/db/utils/locations.py index 309f57d..8b95cba 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 @@ -146,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/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/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", +] diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 763a9f0..cc49669 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 @@ -257,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 @@ -333,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 @@ -426,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 +555,7 @@ 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) @@ -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 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,