Make mypy as strict as practical #13

Merged
alexander merged 32 commits from stricter-mypy into develop 2026-12-01 14:26:52 +01:00
29 changed files with 273 additions and 116 deletions

View file

@ -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)

View file

@ -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"

View file

@ -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())

View file

@ -15,6 +15,13 @@ from velofy import db
from velofy import forecasts
__all__ = [
"config",
"db",
"forecasts",
]
try:
_pkg_info = _metadata.metadata(__name__)

View file

@ -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)

View file

@ -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(

View file

@ -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",
]

View file

@ -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:

View file

@ -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`.

View file

@ -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",
)

View file

@ -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

View file

@ -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."""

View file

@ -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:

View file

@ -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

View file

@ -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:

View file

@ -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",
},
),
)
)

View file

@ -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

View file

@ -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:

View file

@ -2,3 +2,9 @@
from velofy.db.replay.orders import ReplayedOrder
from velofy.db.replay.simulations import ReplaySimulation
__all__ = [
"ReplaySimulation",
"ReplayedOrder",
]

View file

@ -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

Some files were not shown because too many files have changed in this diff Show more