From e30b3efbe8fc719f7d1d5bef32c69df67884f4d7 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 14:17:49 +0100 Subject: [PATCH 01/21] Use the `sa` alias for `sqlalchemy` everywhere `sa` is the common alias, also in SQLAlchemy's own documentation --- tests/db/replay/test_orders.py | 8 ++++---- tests/db/test_addresses.py | 4 ++-- tests/db/test_addresses_addresses.py | 10 +++++----- tests/db/test_addresses_pixels.py | 10 +++++----- tests/db/test_forecasts.py | 4 ++-- tests/db/test_grids.py | 4 ++-- tests/db/test_orders.py | 10 +++++----- tests/db/test_pixels.py | 4 ++-- tests/db/test_restaurants.py | 4 ++-- 9 files changed, 29 insertions(+), 29 deletions(-) diff --git a/tests/db/replay/test_orders.py b/tests/db/replay/test_orders.py index 412416a..8d347f2 100644 --- a/tests/db/replay/test_orders.py +++ b/tests/db/replay/test_orders.py @@ -3,7 +3,7 @@ import datetime as dt import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from tests import config as test_config @@ -44,7 +44,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.ReplaySimulation).where( + stmt = sa.delete(db.ReplaySimulation).where( db.ReplaySimulation.id == replayed_order.simulation.id, ) @@ -60,7 +60,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Order).where(db.Order.id == replayed_order.actual.id) + stmt = sa.delete(db.Order).where(db.Order.id == replayed_order.actual.id) with pytest.raises(sa_exc.IntegrityError, match="fk_replayed_orders_to_orders"): db_session.execute(stmt) @@ -80,7 +80,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Courier).where(db.Courier.id == replayed_order.courier.id) + stmt = sa.delete(db.Courier).where(db.Courier.id == replayed_order.courier.id) with pytest.raises( sa_exc.IntegrityError, diff --git a/tests/db/test_addresses.py b/tests/db/test_addresses.py index 6c3843e..9057657 100644 --- a/tests/db/test_addresses.py +++ b/tests/db/test_addresses.py @@ -1,7 +1,7 @@ """Test the ORM's `Address` model.""" import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from velofy import db @@ -57,7 +57,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.City).where(db.City.id == address.city.id) + stmt = sa.delete(db.City).where(db.City.id == address.city.id) with pytest.raises( sa_exc.IntegrityError, diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index 9d9f91d..087547f 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -4,7 +4,7 @@ import json import googlemaps import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from geopy import distance from sqlalchemy import exc as sa_exc @@ -73,7 +73,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Address).where(db.Address.id == path.first_address.id) + stmt = sa.delete(db.Address).where(db.Address.id == path.first_address.id) with pytest.raises( sa_exc.IntegrityError, @@ -87,7 +87,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Address).where(db.Address.id == path.second_address.id) + stmt = sa.delete(db.Address).where(db.Address.id == path.second_address.id) with pytest.raises( sa_exc.IntegrityError, @@ -103,7 +103,7 @@ class TestConstraints: # Must insert without ORM as otherwise SQLAlchemy figures out # that something is wrong before any query is sent to the database. - stmt = sqla.insert(db.Path).values( + stmt = sa.insert(db.Path).values( first_address_id=address.id, second_address_id=another_address.id, city_id=999, @@ -123,7 +123,7 @@ class TestConstraints: # Must insert without ORM as otherwise SQLAlchemy figures out # that something is wrong before any query is sent to the database. - stmt = sqla.insert(db.Path).values( + stmt = sa.insert(db.Path).values( first_address_id=path.first_address.id, second_address_id=path.second_address.id, city_id=path.city_id, diff --git a/tests/db/test_addresses_pixels.py b/tests/db/test_addresses_pixels.py index 9b38caa..6fa46d9 100644 --- a/tests/db/test_addresses_pixels.py +++ b/tests/db/test_addresses_pixels.py @@ -10,7 +10,7 @@ Implementation notes: """ import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from velofy import db @@ -56,7 +56,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Address).where(db.Address.id == assoc.address.id) + stmt = sa.delete(db.Address).where(db.Address.id == assoc.address.id) with pytest.raises( sa_exc.IntegrityError, @@ -72,7 +72,7 @@ class TestConstraints: # Must insert without ORM as otherwise SQLAlchemy figures out # that something is wrong before any query is sent to the database. - stmt = sqla.insert(db.AddressPixelAssociation).values( + stmt = sa.insert(db.AddressPixelAssociation).values( address_id=address.id, city_id=999, grid_id=pixel.grid.id, @@ -93,7 +93,7 @@ class TestConstraints: # Must insert without ORM as otherwise SQLAlchemy figures out # that something is wrong before any query is sent to the database. - stmt = sqla.insert(db.AddressPixelAssociation).values( + stmt = sa.insert(db.AddressPixelAssociation).values( address_id=address.id, city_id=address.city.id, grid_id=999, @@ -112,7 +112,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Pixel).where(db.Pixel.id == assoc.pixel.id) + stmt = sa.delete(db.Pixel).where(db.Pixel.id == assoc.pixel.id) with pytest.raises( sa_exc.IntegrityError, diff --git a/tests/db/test_forecasts.py b/tests/db/test_forecasts.py index cbc9662..ba6025c 100644 --- a/tests/db/test_forecasts.py +++ b/tests/db/test_forecasts.py @@ -4,7 +4,7 @@ import datetime as dt import pandas as pd import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from tests import config as test_config @@ -76,7 +76,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Pixel).where(db.Pixel.id == forecast.pixel.id) + stmt = sa.delete(db.Pixel).where(db.Pixel.id == forecast.pixel.id) with pytest.raises( sa_exc.IntegrityError, diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index f9433c6..a0f7e30 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -1,7 +1,7 @@ """Test the ORM's `Grid` model.""" import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from velofy import db @@ -41,7 +41,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.City).where(db.City.id == grid.city.id) + stmt = sa.delete(db.City).where(db.City.id == grid.city.id) with pytest.raises( sa_exc.IntegrityError, diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index 7a8c5f5..7ad31f7 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -4,7 +4,7 @@ import datetime as dt import random import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from tests import config as test_config @@ -58,7 +58,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Customer).where(db.Customer.id == order.customer.id) + stmt = sa.delete(db.Customer).where(db.Customer.id == order.customer.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_customers"): db_session.execute(stmt) @@ -69,7 +69,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Courier).where(db.Courier.id == order.courier.id) + stmt = sa.delete(db.Courier).where(db.Courier.id == order.courier.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_couriers"): db_session.execute(stmt) @@ -80,7 +80,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Restaurant).where(db.Restaurant.id == order.restaurant.id) + stmt = sa.delete(db.Restaurant).where(db.Restaurant.id == order.restaurant.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_restaurants"): db_session.execute(stmt) @@ -112,7 +112,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Address).where(db.Address.id == order.delivery_address.id) + stmt = sa.delete(db.Address).where(db.Address.id == order.delivery_address.id) with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_addresses"): db_session.execute(stmt) diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index a7df8c9..bfba927 100644 --- a/tests/db/test_pixels.py +++ b/tests/db/test_pixels.py @@ -1,7 +1,7 @@ """Test the ORM's `Pixel` model.""" import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from velofy import db @@ -41,7 +41,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Grid).where(db.Grid.id == pixel.grid.id) + stmt = sa.delete(db.Grid).where(db.Grid.id == pixel.grid.id) with pytest.raises( sa_exc.IntegrityError, diff --git a/tests/db/test_restaurants.py b/tests/db/test_restaurants.py index 9b07932..a2d6b03 100644 --- a/tests/db/test_restaurants.py +++ b/tests/db/test_restaurants.py @@ -1,7 +1,7 @@ """Test the ORM's `Restaurant` model.""" import pytest -import sqlalchemy as sqla +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from velofy import db @@ -41,7 +41,7 @@ class TestConstraints: db_session.commit() # Must delete without ORM as otherwise an UPDATE statement is emitted. - stmt = sqla.delete(db.Address).where(db.Address.id == restaurant.address.id) + stmt = sa.delete(db.Address).where(db.Address.id == restaurant.address.id) with pytest.raises( sa_exc.IntegrityError, From 78e052b668d029204daeb17d0ded3938156f1f2b Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 14:19:20 +0100 Subject: [PATCH 02/21] Use `sa.func` instead of importing `func` Naming rule for `velofy`: Import modules instead of objects --- src/velofy/console/forecasts.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index 3a5ca60..b8cb965 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -9,7 +9,7 @@ import datetime as dt import sys import click -from sqlalchemy import func +import sqlalchemy as sa from sqlalchemy.orm import exc as orm_exc from velofy import config @@ -105,7 +105,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 # commands are added the make `Forecast`s without the heuristic! # Continue with forecasting on the day the last prediction was made ... last_predict_at = ( - db.session.query(func.max(db.Forecast.start_at)) + db.session.query(sa.func.max(db.Forecast.start_at)) .join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id) .join(db.Grid, db.Pixel.grid_id == db.Grid.id) .filter(db.Forecast.pixel == pixel) From 9d3af5e44719c88e4115c429d38e9e795de5bf05 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 14:21:01 +0100 Subject: [PATCH 03/21] Import the `postgresql` dialect as `psql` --- ...806_23_f11cd76d2f45_create_the_database.py | 22 +++++++++---------- ..._19_e40623e10405_add_demand_forecasting.py | 4 ++-- ...9_add_confidence_intervals_to_forecasts.py | 10 ++++----- ...301_16_b4dd0b8903a5_add_distance_matrix.py | 4 ++-- src/velofy/db/addresses.py | 6 ++--- src/velofy/db/addresses_addresses.py | 4 ++-- src/velofy/db/cities.py | 14 ++++++------ src/velofy/db/couriers.py | 4 ++-- src/velofy/db/forecasts.py | 12 +++++----- src/velofy/db/orders.py | 4 ++-- 10 files changed, 42 insertions(+), 42 deletions(-) diff --git a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py index f4ff769..1e4cf9c 100644 --- a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py +++ b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py @@ -7,7 +7,7 @@ import os import sqlalchemy as sa from alembic import op -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy import configuration @@ -29,12 +29,12 @@ def upgrade(): sa.Column("id", sa.SmallInteger(), autoincrement=False, nullable=False), sa.Column("name", sa.Unicode(length=10), nullable=False), sa.Column("kml", sa.UnicodeText(), nullable=False), - sa.Column("center_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column("center_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column("northeast_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column("northeast_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column("southwest_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column("southwest_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("center_latitude", psql.DOUBLE_PRECISION(), nullable=False), + sa.Column("center_longitude", psql.DOUBLE_PRECISION(), nullable=False), + sa.Column("northeast_latitude", psql.DOUBLE_PRECISION(), nullable=False), + sa.Column("northeast_longitude", psql.DOUBLE_PRECISION(), nullable=False), + sa.Column("southwest_latitude", psql.DOUBLE_PRECISION(), nullable=False), + sa.Column("southwest_longitude", psql.DOUBLE_PRECISION(), nullable=False), sa.Column("initial_zoom", sa.SmallInteger(), nullable=False), sa.PrimaryKeyConstraint("id", name=op.f("pk_cities")), *( @@ -57,7 +57,7 @@ def upgrade(): sa.Column("id", sa.Integer(), autoincrement=False, nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("vehicle", sa.Unicode(length=10), nullable=False), - sa.Column("speed", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("speed", psql.DOUBLE_PRECISION(), nullable=False), sa.Column("capacity", sa.SmallInteger(), nullable=False), sa.Column("pay_per_hour", sa.SmallInteger(), nullable=False), sa.Column("pay_per_order", sa.SmallInteger(), nullable=False), @@ -109,8 +109,8 @@ def upgrade(): sa.Column("primary_id", sa.Integer(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("place_id", sa.Unicode(length=120), nullable=False), - sa.Column("latitude", postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column("longitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("latitude", psql.DOUBLE_PRECISION(), nullable=False), + sa.Column("longitude", psql.DOUBLE_PRECISION(), nullable=False), sa.Column("city_id", sa.SmallInteger(), nullable=False), sa.Column("city", sa.Unicode(length=25), nullable=False), sa.Column("zip_code", sa.Integer(), nullable=False), @@ -277,7 +277,7 @@ def upgrade(): sa.Column("delivery_not_confirmed", sa.Boolean(), nullable=True), sa.Column("courier_waited_at_delivery", sa.Boolean(), nullable=True), sa.Column("logged_delivery_distance", sa.SmallInteger(), nullable=True), - sa.Column("logged_avg_speed", postgresql.DOUBLE_PRECISION(), nullable=True), + sa.Column("logged_avg_speed", psql.DOUBLE_PRECISION(), nullable=True), sa.Column("logged_avg_speed_distance", sa.SmallInteger(), nullable=True), sa.CheckConstraint( "0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900", diff --git a/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py b/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py index 71b353b..a5d0dfe 100644 --- a/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py +++ b/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py @@ -8,7 +8,7 @@ import os import sqlalchemy as sa from alembic import op -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy import configuration @@ -32,7 +32,7 @@ def upgrade(): sa.Column("time_step", sa.SmallInteger(), nullable=False), sa.Column("training_horizon", sa.SmallInteger(), nullable=False), sa.Column("method", sa.Unicode(length=20), nullable=False), - sa.Column("prediction", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("prediction", psql.DOUBLE_PRECISION(), nullable=False), sa.PrimaryKeyConstraint("id", name=op.f("pk_forecasts")), sa.ForeignKeyConstraint( ["pixel_id"], diff --git a/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py b/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py index 5a85485..c134474 100644 --- a/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py +++ b/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py @@ -8,7 +8,7 @@ import os import sqlalchemy as sa from alembic import op -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy import configuration @@ -32,22 +32,22 @@ def upgrade(): ) op.add_column( "forecasts", - sa.Column("low80", postgresql.DOUBLE_PRECISION(), nullable=True), + sa.Column("low80", psql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.add_column( "forecasts", - sa.Column("high80", postgresql.DOUBLE_PRECISION(), nullable=True), + sa.Column("high80", psql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.add_column( "forecasts", - sa.Column("low95", postgresql.DOUBLE_PRECISION(), nullable=True), + sa.Column("low95", psql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.add_column( "forecasts", - sa.Column("high95", postgresql.DOUBLE_PRECISION(), nullable=True), + sa.Column("high95", psql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.create_check_constraint( diff --git a/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py b/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py index a99d55e..d4c3fb0 100644 --- a/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py +++ b/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py @@ -8,7 +8,7 @@ import os import sqlalchemy as sa from alembic import op -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy import configuration @@ -32,7 +32,7 @@ def upgrade(): sa.Column("air_distance", sa.Integer(), nullable=False), sa.Column("bicycle_distance", sa.Integer(), nullable=True), sa.Column("bicycle_duration", sa.Integer(), nullable=True), - sa.Column("directions", postgresql.JSON(), nullable=True), + sa.Column("directions", psql.JSON(), nullable=True), sa.PrimaryKeyConstraint( "first_address_id", "second_address_id", diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 4cddf20..65bc760 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -9,7 +9,7 @@ from typing import Any import folium import sqlalchemy as sa from sqlalchemy import orm -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from sqlalchemy.ext import hybrid from velofy import config @@ -43,11 +43,11 @@ class Address(meta.Base): index=True, ) latitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) longitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) city_id: orm.Mapped[int] = orm.mapped_column( diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 682f111..83500a4 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -13,7 +13,7 @@ import ordered_set import sqlalchemy as sa from geopy import distance as geo_distance from sqlalchemy import orm -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy import config from velofy import db @@ -68,7 +68,7 @@ class Path(meta.Base): # An array of latitude-longitude pairs approximating a courier's way. _directions: orm.Mapped[str | None] = orm.mapped_column( "directions", - postgresql.JSON, + psql.JSON, nullable=True, ) diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index ce7b8b9..9fc9633 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -7,7 +7,7 @@ import functools import folium import sqlalchemy as sa from sqlalchemy import orm -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy import config from velofy import db @@ -37,27 +37,27 @@ class City(meta.Base): # Google Maps related columns center_latitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) center_longitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) northeast_latitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) northeast_longitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) southwest_latitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) southwest_longitude: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) initial_zoom: orm.Mapped[int] = orm.mapped_column( diff --git a/src/velofy/db/couriers.py b/src/velofy/db/couriers.py index 94ad329..2c3aeb9 100644 --- a/src/velofy/db/couriers.py +++ b/src/velofy/db/couriers.py @@ -4,7 +4,7 @@ import datetime as dt import sqlalchemy as sa from sqlalchemy import orm -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy.db import meta @@ -30,7 +30,7 @@ class Courier(meta.Base): ) historic_speed: orm.Mapped[float] = orm.mapped_column( "speed", - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) capacity: orm.Mapped[int] = orm.mapped_column( diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index f33a0dd..2ab4c14 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -9,7 +9,7 @@ from typing import List import pandas as pd import sqlalchemy as sa from sqlalchemy import orm -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy.db import meta @@ -60,25 +60,25 @@ class Forecast(meta.Base): # Raw `.prediction`s are stored as `float`s (possibly negative). # The rounding is then done on the fly if required. prediction: orm.Mapped[float] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=False, ) # The confidence intervals are treated like the `.prediction`s # but they may be nullable as some methods do not calculate them. low80: orm.Mapped[float | None] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=True, ) high80: orm.Mapped[float | None] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=True, ) low95: orm.Mapped[float | None] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=True, ) high95: orm.Mapped[float | None] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=True, ) diff --git a/src/velofy/db/orders.py b/src/velofy/db/orders.py index 32e2a97..189d30a 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -5,7 +5,7 @@ import datetime as dt import folium import sqlalchemy as sa from sqlalchemy import orm -from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import postgresql as psql from velofy import config from velofy import db @@ -233,7 +233,7 @@ class Order(meta.Base): nullable=True, ) logged_avg_speed: orm.Mapped[float | None] = orm.mapped_column( - postgresql.DOUBLE_PRECISION, + psql.DOUBLE_PRECISION, nullable=True, ) logged_avg_speed_distance: orm.Mapped[int | None] = orm.mapped_column( From 0b2a1197a2b089120f66ae2c8c365fac983192f4 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 14:22:42 +0100 Subject: [PATCH 04/21] Import `sqlalchemy.ext.hybrid` as `sa_hybrid` --- src/velofy/db/addresses.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 65bc760..00238a6 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -10,7 +10,7 @@ import folium import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql -from sqlalchemy.ext import hybrid +from sqlalchemy.ext import hybrid as sa_hybrid from velofy import config from velofy.db import meta @@ -124,7 +124,7 @@ class Address(meta.Base): """Non-literal text representation.""" return f"<{self.__class__.__name__}({self.street} in {self.city_name})>" - @hybrid.hybrid_property + @sa_hybrid.hybrid_property def is_primary(self) -> bool: """If an `Address` object is the earliest one entered at its location. From aa1a7c796f9ea9791a21ea87b0f1a178cc2ccc90 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 14:56:11 +0100 Subject: [PATCH 05/21] Register the shared fixtures via `pytest_plugins` That is the documented way to share fixtures from other modules, instead of importing them into tests/conftest.py --- tests/conftest.py | 33 ++++++++------------------------- tests/db/fake_data/__init__.py | 20 -------------------- 2 files changed, 8 insertions(+), 45 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 4ea0d8b..ebd7fc8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,11 +12,18 @@ from alembic import command as migrations_cmd from alembic import config as migrations_config from sqlalchemy import orm -from tests.db import fake_data from velofy import config from velofy import db +# Register the shared fixtures in `tests.db.fake_data` here, +# as tests/console/, tests/db/, and tests/forecasts/ use them +pytest_plugins = [ + "tests.db.fake_data.fixture_makers", + "tests.db.fake_data.static_fixtures", +] + + # The TESTING environment variable is set # in pyproject.toml in pytest's config section. if not os.getenv("TESTING"): @@ -100,27 +107,3 @@ def db_session(db_connection): session.close() transaction.rollback() - - -# Import the fixtures from the `fake_data` sub-package. - -make_address = fake_data.make_address -make_courier = fake_data.make_courier -make_customer = fake_data.make_customer -make_order = fake_data.make_order -make_replay_order = fake_data.make_replay_order -make_restaurant = fake_data.make_restaurant - -address = fake_data.address -city = fake_data.city -city_data = fake_data.city_data -courier = fake_data.courier -customer = fake_data.customer -order = fake_data.order -pre_order = fake_data.pre_order -replayed_order = fake_data.replayed_order -restaurant = fake_data.restaurant -grid = fake_data.grid -pixel = fake_data.pixel -simulation = fake_data.simulation -simulation_data = fake_data.simulation_data diff --git a/tests/db/fake_data/__init__.py b/tests/db/fake_data/__init__.py index 0fc9433..66768fa 100644 --- a/tests/db/fake_data/__init__.py +++ b/tests/db/fake_data/__init__.py @@ -1,21 +1 @@ """Fixtures for testing the ORM layer with fake data.""" - -from tests.db.fake_data.fixture_makers import make_address -from tests.db.fake_data.fixture_makers import make_courier -from tests.db.fake_data.fixture_makers import make_customer -from tests.db.fake_data.fixture_makers import make_order -from tests.db.fake_data.fixture_makers import make_replay_order -from tests.db.fake_data.fixture_makers import make_restaurant -from tests.db.fake_data.static_fixtures import address -from tests.db.fake_data.static_fixtures import city -from tests.db.fake_data.static_fixtures import city_data -from tests.db.fake_data.static_fixtures import courier -from tests.db.fake_data.static_fixtures import customer -from tests.db.fake_data.static_fixtures import grid -from tests.db.fake_data.static_fixtures import order -from tests.db.fake_data.static_fixtures import pixel -from tests.db.fake_data.static_fixtures import pre_order -from tests.db.fake_data.static_fixtures import replayed_order -from tests.db.fake_data.static_fixtures import restaurant -from tests.db.fake_data.static_fixtures import simulation -from tests.db.fake_data.static_fixtures import simulation_data From c6518f6b39386a7c803d0c2792fdae6d61436064 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 15:07:38 +0100 Subject: [PATCH 06/21] Use builtin generics and `X | None` Since Python 3.9 and 3.10, `list`, `tuple`, and `X | None` replace `typing.List`, `typing.Tuple`, and `typing.Optional` --- noxfile.py | 3 ++- src/velofy/console/decorators.py | 3 ++- src/velofy/db/addresses_addresses.py | 7 +++---- src/velofy/db/forecasts.py | 3 +-- src/velofy/db/pixels.py | 3 +-- src/velofy/db/utils/locations.py | 10 ++++------ src/velofy/forecasts/methods/decomposition.py | 11 +++++------ src/velofy/forecasts/timify.py | 7 +++---- 8 files changed, 21 insertions(+), 26 deletions(-) diff --git a/noxfile.py b/noxfile.py index 68307b1..0cbe35e 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,9 @@ import itertools import os import pathlib import tempfile +from collections.abc import Generator from collections.abc import Mapping -from typing import Any, Generator +from typing import Any import nox from nox.sessions import Session diff --git a/src/velofy/console/decorators.py b/src/velofy/console/decorators.py index 513882a..19cbd6d 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -4,7 +4,8 @@ import functools import os import subprocess # noqa:S404 import sys -from typing import Any, Callable +from collections.abc import Callable +from typing import Any import click diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index 83500a4..ee5415d 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -5,7 +5,6 @@ from __future__ import annotations import functools import itertools import json -from typing import List, Tuple import folium import googlemaps as gm @@ -127,7 +126,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. @@ -239,7 +238,7 @@ class Path(meta.Base): # get from A to B. As a step's "start_location" may equal the previous step's # "end_location", we use an `OrderedSet` to find the unique latitude-longitude # pairs that make up the path from `.first_address` to `.second_address`. - steps: ordered_set.OrderedSet[Tuple[float, float]] = ordered_set.OrderedSet() + steps: ordered_set.OrderedSet[tuple[float, float]] = ordered_set.OrderedSet() for step in route["steps"]: steps.add( (step["start_location"]["lat"], step["start_location"]["lng"]), @@ -262,7 +261,7 @@ class Path(meta.Base): return self.first_address.city.map @functools.cached_property - def waypoints(self) -> List[utils.Location]: + def waypoints(self) -> list[utils.Location]: """The couriers' route from `.first_address` to `.second_address`. The returned `Location`s all relate to `.first_address.city.southwest`. diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 2ab4c14..45717e8 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -4,7 +4,6 @@ from __future__ import annotations import datetime as dt import math -from typing import List import pandas as pd import sqlalchemy as sa @@ -193,7 +192,7 @@ class Forecast(meta.Base): 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/pixels.py b/src/velofy/db/pixels.py index 96cf050..61d155a 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -3,7 +3,6 @@ from __future__ import annotations import functools -from typing import List import folium import sqlalchemy as sa @@ -131,7 +130,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) diff --git a/src/velofy/db/utils/locations.py b/src/velofy/db/utils/locations.py index 21b4eef..df7ef6b 100644 --- a/src/velofy/db/utils/locations.py +++ b/src/velofy/db/utils/locations.py @@ -2,8 +2,6 @@ from __future__ import annotations -from typing import Optional, Tuple - import utm @@ -38,8 +36,8 @@ class Location: self._zone = zone self._band = band.upper() - self._normalized_easting: Optional[int] = None - self._normalized_northing: Optional[int] = None + self._normalized_easting: int | None = None + self._normalized_northing: int | None = None def __repr__(self) -> str: """A non-literal text representation in the UTM system. @@ -72,7 +70,7 @@ class Location: return self._longitude @property - def lat_lng(self) -> Tuple[float, float]: + def lat_lng(self) -> tuple[float, float]: """The `.latitude` and `.longitude` as a 2-`tuple`.""" return self._latitude, self._longitude @@ -92,7 +90,7 @@ class Location: return f"{self._zone}{self._band}" @property - def zone_details(self) -> Tuple[int, str]: + def zone_details(self) -> tuple[int, str]: """The UTM zone of the location as the zone number and the band.""" return self._zone, self._band diff --git a/src/velofy/forecasts/methods/decomposition.py b/src/velofy/forecasts/methods/decomposition.py index 5d5d827..b77934f 100644 --- a/src/velofy/forecasts/methods/decomposition.py +++ b/src/velofy/forecasts/methods/decomposition.py @@ -5,7 +5,6 @@ using the `rpy2` library. """ import math -from typing import Optional import pandas as pd from rpy2 import robjects @@ -17,14 +16,14 @@ def stl( # noqa:C901,PLR0912,PLR0913,PLR0915 *, frequency: int, ns: int, - nt: Optional[int] = None, - nl: Optional[int] = None, + nt: int | None = None, + nl: int | None = None, ds: int = 0, dt: int = 1, dl: int = 1, - js: Optional[int] = None, - jt: Optional[int] = None, - jl: Optional[int] = None, + js: int | None = None, + jt: int | None = None, + jl: int | None = None, ni: int = 2, no: int = 0, ) -> pd.DataFrame: diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 826afc6..457e0a5 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -3,7 +3,6 @@ from __future__ import annotations import datetime as dt -from typing import Tuple import pandas as pd import sqlalchemy as sa @@ -244,7 +243,7 @@ class OrderHistory: pixel_id: int, predict_at: dt.datetime, train_horizon: int, - ) -> Tuple[pd.Series, int, pd.Series]: + ) -> tuple[pd.Series, int, pd.Series]: """Slice a horizontal time series out of the `.totals`. Create a time series covering `train_horizon` weeks that can be used @@ -316,7 +315,7 @@ class OrderHistory: pixel_id: int, predict_day: dt.date, train_horizon: int, - ) -> Tuple[pd.Series, int, pd.Series]: + ) -> tuple[pd.Series, int, pd.Series]: """Slice a vertical time series out of the `.totals`. Create a time series covering `train_horizon` weeks that can be used @@ -405,7 +404,7 @@ class OrderHistory: pixel_id: int, predict_at: dt.datetime, train_horizon: int, - ) -> Tuple[pd.Series, int, pd.Series]: + ) -> tuple[pd.Series, int, pd.Series]: """Slice a vertical real-time time series out of the `.totals`. Create a time series covering `train_horizon` weeks that can be used From 9c3b52befb51f91026accb9d4d3e0874ef6c3d23 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 15:10:29 +0100 Subject: [PATCH 07/21] Import `typing` as `t` ... ... and `collections.abc` as `cabc` Linting rule for `velofy`: Import modules instead of objects --- noxfile.py | 17 ++++++++--------- src/velofy/console/decorators.py | 15 +++++++-------- src/velofy/console/main.py | 4 ++-- src/velofy/db/addresses.py | 6 +++--- src/velofy/db/connection.py | 4 ++-- src/velofy/db/grids.py | 4 ++-- src/velofy/db/meta.py | 4 ++-- 7 files changed, 26 insertions(+), 28 deletions(-) diff --git a/noxfile.py b/noxfile.py index 0cbe35e..1fc09ca 100644 --- a/noxfile.py +++ b/noxfile.py @@ -23,20 +23,19 @@ e.g., `uv run nox -s test -- tests/test_config.py`. """ import collections +import collections.abc as cabc import itertools import os import pathlib import tempfile -from collections.abc import Generator -from collections.abc import Mapping -from typing import Any +import typing as t import nox from nox.sessions import Session from packaging import version as pkg_version -def nested_defaultdict() -> collections.defaultdict[str, Any]: +def nested_defaultdict() -> collections.defaultdict[str, t.Any]: """Create a multi-level `defaultdict` with variable depth. The returned `dict`ionary never raises a `KeyError` @@ -48,9 +47,9 @@ def nested_defaultdict() -> collections.defaultdict[str, Any]: return collections.defaultdict(nested_defaultdict) -def defaultify(obj: Any) -> Any: +def defaultify(obj: t.Any) -> t.Any: """Turn nested `dict`s into nested `defaultdict`s.""" - if isinstance(obj, Mapping): + if isinstance(obj, cabc.Mapping): return collections.defaultdict( nested_defaultdict, {key: defaultify(val) for key, val in obj.items()}, @@ -58,7 +57,7 @@ def defaultify(obj: Any) -> Any: return obj -def load_pyproject_toml() -> collections.defaultdict[str, Any]: +def load_pyproject_toml() -> collections.defaultdict[str, t.Any]: """Load the contents of the pyproject.toml file. The contents are represented as a `nested_defaultdict`; @@ -522,7 +521,7 @@ def clean_cwd(session: Session) -> None: session.run("rm", "-rf", path) -def _expand(*patterns: str) -> Generator[pathlib.Path, None, None]: +def _expand(*patterns: str) -> cabc.Generator[pathlib.Path, None, None]: """Expand glob patterns into (resolved) paths. Args: @@ -600,7 +599,7 @@ def start(session: Session) -> None: def install_pinned( session: Session, *packages_or_pip_args: str, - **kwargs: Any, + **kwargs: t.Any, ) -> None: """Install packages respecting the uv.lock file. diff --git a/src/velofy/console/decorators.py b/src/velofy/console/decorators.py index 19cbd6d..4c9a5d9 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -1,25 +1,24 @@ """Utils for the CLI scripts.""" +import collections.abc as cabc import functools import os import subprocess # noqa:S404 import sys -from collections.abc import Callable -from typing import Any +import typing as t import click -def db_revision( - rev: str, -) -> Callable[..., Callable[..., Any]]: # pragma: no cover -> easy to check visually +def db_revision(rev: str) -> cabc.Callable[..., cabc.Callable[..., t.Any]]: """A decorator ensuring the database is at a given revision.""" - def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + def decorator(func: cabc.Callable[..., t.Any]) -> cabc.Callable[..., t.Any]: @functools.wraps(func) - def ensure(*args: Any, **kwargs: Any) -> Any: + def ensure(*args: t.Any, **kwargs: t.Any) -> t.Any: """Do not execute the `func` if the revision does not match.""" - if not os.getenv("TESTING"): + # Skip in tests as the database then either has no or the latest revision + if not os.getenv("TESTING"): # pragma: no cover result = subprocess.run( # noqa:S603,S607 ["alembic", "current"], # noqa:S607 capture_output=True, diff --git a/src/velofy/console/main.py b/src/velofy/console/main.py index 0874530..8446905 100644 --- a/src/velofy/console/main.py +++ b/src/velofy/console/main.py @@ -1,6 +1,6 @@ """The entry point for all CLI scripts in the project.""" -from typing import Any +import typing as t import click from click import core as cli_core @@ -8,7 +8,7 @@ from click import core as cli_core import velofy -def show_version(ctx: cli_core.Context, _param: Any, value: bool) -> None: +def show_version(ctx: cli_core.Context, _param: t.Any, value: bool) -> None: """Show the package's version.""" # If --version / -V is NOT passed in, # continue with the command. diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 00238a6..34564a1 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -4,7 +4,7 @@ from __future__ import annotations import datetime as dt import functools -from typing import Any +import typing as t import folium import sqlalchemy as sa @@ -185,7 +185,7 @@ class Address(meta.Base): """Shortcut to the `.city.map` object.""" return self.city.map - def draw(self, **kwargs: Any) -> folium.Map: # pragma: no cover + def draw(self, **kwargs: t.Any) -> folium.Map: # pragma: no cover """Draw the address on the `.city.map`. By default, addresses are shown as black dots. @@ -197,7 +197,7 @@ class Address(meta.Base): Returns: `.city.map` for convenience in interactive usage """ - defaults: dict[str, Any] = { + defaults: dict[str, t.Any] = { "color": f"{config.NEUTRAL_COLOR}", "popup": f"{self.street}, {self.zip_code} {self.city_name}", } diff --git a/src/velofy/db/connection.py b/src/velofy/db/connection.py index 3ca9d5c..1e29d81 100644 --- a/src/velofy/db/connection.py +++ b/src/velofy/db/connection.py @@ -8,7 +8,7 @@ That is the case on the CI server. """ import os -from typing import cast +import typing as t import sqlalchemy as sa from sqlalchemy import orm @@ -21,5 +21,5 @@ if os.getenv("TESTING"): session: orm.Session = None # type: ignore[assignment] else: # pragma: no cover - engine = sa.create_engine(cast(str, velofy.config.DATABASE_URI)) + engine = sa.create_engine(t.cast(str, velofy.config.DATABASE_URI)) session = orm.Session(bind=engine) diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index 9821ade..ec8802e 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Any +import typing as t import folium import sqlalchemy as sa @@ -136,7 +136,7 @@ class Grid(meta.Base): """Shortcut to the `.city.map` object.""" return self.city.map - def draw(self, **kwargs: Any) -> folium.Map: # pragma: no cover + def draw(self, **kwargs: t.Any) -> folium.Map: # pragma: no cover """Draw all pixels in the grid. Args: diff --git a/src/velofy/db/meta.py b/src/velofy/db/meta.py index ff86eb2..3901514 100644 --- a/src/velofy/db/meta.py +++ b/src/velofy/db/meta.py @@ -1,6 +1,6 @@ """Provide the ORM's declarative base.""" -from typing import Any +import typing as t import sqlalchemy as sa from sqlalchemy import orm @@ -8,7 +8,7 @@ from sqlalchemy import orm import velofy -Base: Any = orm.declarative_base( +Base: t.Any = orm.declarative_base( metadata=sa.MetaData( schema=velofy.config.CLEAN_SCHEMA, naming_convention={ From f0c617955bc8e9d46cd4126e0a334f1a28cc7849 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 15:43:09 +0100 Subject: [PATCH 08/21] Use the `nox` module import --- noxfile.py | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/noxfile.py b/noxfile.py index 1fc09ca..14897d5 100644 --- a/noxfile.py +++ b/noxfile.py @@ -31,7 +31,6 @@ import tempfile import typing as t import nox -from nox.sessions import Session from packaging import version as pkg_version @@ -140,7 +139,7 @@ os.makedirs(tempfile.tempdir, exist_ok=True) @nox.session(name="format", python=MAIN_PYTHON) -def format_code(session: Session) -> None: +def format_code(session: nox.Session) -> None: """Format source files with `autoflake`, `black`, `flynt`, `isort`, and `ruff`. If no extra arguments are provided, all source files are formatted. @@ -175,7 +174,7 @@ def format_code(session: Session) -> None: @nox.session(name="lint", python=MAIN_PYTHON) -def lint_code(session: Session) -> None: +def lint_code(session: nox.Session) -> None: """Lint source files with `flake8`, `isort`, `mypy`, and `ruff`. If no extra arguments are provided, all source files are linted. @@ -233,7 +232,7 @@ def lint_code(session: Session) -> None: @nox.session(name="test", python=MAIN_PYTHON) -def test_code(session: Session) -> None: +def test_code(session: nox.Session) -> None: """Run the unit and integration tests with `pytest`. If no extra arguments are provided, the entire test suite @@ -271,7 +270,7 @@ def test_code(session: Session) -> None: @nox.session(name="doctest", python=MAIN_PYTHON) -def test_docstrings(session: Session) -> None: +def test_docstrings(session: nox.Session) -> None: """Test the code snippets in the docstrings with `xdoctest`. By default, all docstrings in the package are checked. @@ -296,7 +295,7 @@ def test_docstrings(session: Session) -> None: @nox.session(name="docs", python=MAIN_PYTHON) -def build_docs(session: Session) -> None: +def build_docs(session: nox.Session) -> None: """Build the documentation with `sphinx`. Also, verify that all external links work. @@ -320,7 +319,7 @@ def build_docs(session: Session) -> None: @nox.session(name="venv", python=MAIN_PYTHON, venv_backend="none") -def create_develop_environment(session: Session) -> None: +def create_develop_environment(session: nox.Session) -> None: """Set up the local develop environment in ".venv". All dependency groups and extras are installed @@ -350,7 +349,7 @@ def create_develop_environment(session: Session) -> None: @nox.session(name="deps-audit", python=MAIN_PYTHON, reuse_venv=False) -def audit_pinned_dependencies(session: Session) -> None: +def audit_pinned_dependencies(session: nox.Session) -> None: """Check dependencies for vulnerabilities with `pip-audit`. The dependencies are all those pinned in the uv.lock file. @@ -394,7 +393,7 @@ def audit_pinned_dependencies(session: Session) -> None: @nox.session(name="deps-lock", python=MAIN_PYTHON, venv_backend="none") -def lock_dependencies(session: Session) -> None: +def lock_dependencies(session: nox.Session) -> None: """Lock dependencies in pyproject.toml into uv.lock. Convenience task to run after manual changes of dependencies @@ -414,7 +413,7 @@ def lock_dependencies(session: Session) -> None: @nox.session(name="deps-upgrade", python=MAIN_PYTHON, venv_backend="none") -def upgrade_dependencies(session: Session) -> None: +def upgrade_dependencies(session: nox.Session) -> None: """Pin dependencies in uv.lock to their latest MINOR/PATCH versions. The allowed versions are the ranges in the pyproject.toml file. @@ -447,7 +446,7 @@ def upgrade_dependencies(session: Session) -> None: @nox.session(name="deps-upgrade-check", python=MAIN_PYTHON) -def check_dependency_upgrades(session: Session) -> None: +def check_dependency_upgrades(session: nox.Session) -> None: """Check the dependencies in uv.lock for upgrades. This task checks if upgrades are available for the PyPI @@ -465,7 +464,7 @@ def check_dependency_upgrades(session: Session) -> None: @nox.session(name="init-project", python=MAIN_PYTHON, venv_backend="none") -def initialize_project(session: Session) -> None: +def initialize_project(session: nox.Session) -> None: """Install the `pre-commit` hooks and configure `git blame`.""" # .pre-commit-config.yaml sets the hook types via "default_install_hook_types" session.run("uv", "run", "pre-commit", "install") @@ -481,7 +480,7 @@ def initialize_project(session: Session) -> None: @nox.session(name="clean-cwd", python=MAIN_PYTHON, venv_backend="none") -def clean_cwd(session: Session) -> None: +def clean_cwd(session: nox.Session) -> None: """Remove (almost) all glob patterns listed in git's ignore file. Compared to `git clean -X`, never remove local environment variables @@ -540,7 +539,7 @@ def _expand(*patterns: str) -> cabc.Generator[pathlib.Path, None, None]: yield path.resolve() -def do_not_accept_arguments(session: Session, *, raise_error: bool = True) -> None: +def do_not_accept_arguments(session: nox.Session, *, raise_error: bool = True) -> None: """Do not accept any `session.posargs`.""" if session.posargs: msg = 'be run without any positional arguments behind the "--"' @@ -551,7 +550,7 @@ def do_not_accept_arguments(session: Session, *, raise_error: bool = True) -> No session.warn(f"Should {msg}") -def do_not_reuse(session: Session, *, raise_error: bool = True) -> None: +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: msg = 'be run without the "-r" and "-R" flags' @@ -562,7 +561,7 @@ def do_not_reuse(session: Session, *, raise_error: bool = True) -> None: session.warn(f"Should {msg}") -def start(session: Session) -> None: +def start(session: nox.Session) -> None: """Show generic info about a session.""" if session.posargs: session.debug(f"Received extra arguments: {session.posargs}") @@ -597,7 +596,7 @@ def start(session: Session) -> None: def install_pinned( - session: Session, + session: nox.Session, *packages_or_pip_args: str, **kwargs: t.Any, ) -> None: @@ -634,7 +633,7 @@ def install_pinned( ) -def skip_install(session: Session) -> bool: +def skip_install(session: nox.Session) -> bool: """Installations may be skipped if a virtual environment can be reused. Skipping package installations must be requested with the "-R" flag. From 5ca16ae47c63c06ac67b11908f813a544c377670 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 15:50:17 +0100 Subject: [PATCH 09/21] Import `datetime` as `dt` everywhere --- scripts/get_update_info_for_dependencies.py | 8 +++--- src/velofy/configuration.py | 6 ++--- .../forecasts/timify/test_aggregate_orders.py | 26 +++++++++---------- .../forecasts/timify/test_make_time_series.py | 10 +++---- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/scripts/get_update_info_for_dependencies.py b/scripts/get_update_info_for_dependencies.py index c6d565e..c9d2010 100755 --- a/scripts/get_update_info_for_dependencies.py +++ b/scripts/get_update_info_for_dependencies.py @@ -8,7 +8,7 @@ uv.lock file are out-of-date and how long ago releases were published. It is run as part of the "deps-upgrade-check" `nox` session. """ -import datetime +import datetime as dt import http.client import json import pathlib @@ -77,9 +77,9 @@ def get_years_since_release( latest_version = data["info"]["version"] release_date = infos_for_pinned_release[0]["upload_time"] - release_date = datetime.datetime.fromisoformat(release_date.replace("Z", "+00:00")) + release_date = dt.datetime.fromisoformat(release_date.replace("Z", "+00:00")) - years_since_release = (datetime.datetime.now() - release_date).days / 365.25 + years_since_release = (dt.datetime.now() - release_date).days / 365.25 return round(years_since_release, 1), latest_version @@ -116,7 +116,7 @@ def make_comment( def write_report(lines: list[tuple[str, bool]]) -> None: """Write all lines to the report file and the noteworthy ones to the CLI.""" header = f""" - # Created on: {datetime.date.today()} + # Created on: {dt.date.today()} # # The versions pinned in the uv.lock file are amended with information # regarding the latest available version on PyPI and the no. of years diff --git a/src/velofy/configuration.py b/src/velofy/configuration.py index 44cf262..6dbdfa9 100644 --- a/src/velofy/configuration.py +++ b/src/velofy/configuration.py @@ -7,7 +7,7 @@ Within this package, use the `config` proxy at the package's top level to access the current configuration! """ -import datetime +import datetime as dt import os import random import string @@ -28,11 +28,11 @@ class Config: # ----------------------------- # Date after which the real-life data is discarded. - CUTOFF_DAY = datetime.datetime(2017, 2, 1) + CUTOFF_DAY = dt.datetime(2017, 2, 1) # If a scheduled pre-order is made within this # time horizon, we treat it as an ad-hoc order. - QUASI_AD_HOC_LIMIT = datetime.timedelta(minutes=45) + QUASI_AD_HOC_LIMIT = dt.timedelta(minutes=45) # Operating hours of the platform. SERVICE_START = 11 diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 2fb1db1..534aee5 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -1,6 +1,6 @@ """Test the `OrderHistory.aggregate_orders()` method.""" -import datetime +import datetime as dt import pytest @@ -78,7 +78,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant, - placed_at=datetime.datetime(*test_config.DATE, hour, 11), + placed_at=dt.datetime(*test_config.DATE, hour, 11), ) db_session.add(order) @@ -112,7 +112,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant, - placed_at=datetime.datetime(*test_config.DATE, hour, 11), + placed_at=dt.datetime(*test_config.DATE, hour, 11), ) db_session.add(order) @@ -148,7 +148,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant, - placed_at=datetime.datetime(*test_config.DATE, hour, 11), + placed_at=dt.datetime(*test_config.DATE, hour, 11), ) db_session.add(order) @@ -183,15 +183,15 @@ class TestAggregateOrders: ad_hoc_order = make_order( scheduled=False, restaurant=restaurant, - placed_at=datetime.datetime(*test_config.DATE, 11, 11), + placed_at=dt.datetime(*test_config.DATE, 11, 11), ) db_session.add(ad_hoc_order) pre_order = make_order( scheduled=True, restaurant=restaurant, - placed_at=datetime.datetime(*test_config.DATE, 9, 0), - scheduled_delivery_at=datetime.datetime(*test_config.DATE, 12, 0), + placed_at=dt.datetime(*test_config.DATE, 9, 0), + scheduled_delivery_at=dt.datetime(*test_config.DATE, 12, 0), ) db_session.add(pre_order) @@ -228,7 +228,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant, - placed_at=datetime.datetime(*test_config.DATE, hour, 11), + placed_at=dt.datetime(*test_config.DATE, hour, 11), ) db_session.add(order) @@ -268,7 +268,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant, - placed_at=datetime.datetime(*test_config.DATE, hour, 11), + placed_at=dt.datetime(*test_config.DATE, hour, 11), ) db_session.add(order) @@ -277,7 +277,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant, - placed_at=datetime.datetime( + placed_at=dt.datetime( test_config.YEAR, test_config.MONTH, test_config.DAY + 1, @@ -356,7 +356,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant1, - placed_at=datetime.datetime(*test_config.DATE, hour, 11), + placed_at=dt.datetime(*test_config.DATE, hour, 11), ) db_session.add(order) @@ -365,7 +365,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant2, - placed_at=datetime.datetime( + placed_at=dt.datetime( test_config.YEAR, test_config.MONTH, test_config.DAY, @@ -378,7 +378,7 @@ class TestAggregateOrders: order = make_order( scheduled=False, restaurant=restaurant2, - placed_at=datetime.datetime( + placed_at=dt.datetime( test_config.YEAR, test_config.MONTH, test_config.DAY, diff --git a/tests/forecasts/timify/test_make_time_series.py b/tests/forecasts/timify/test_make_time_series.py index 2d4a105..fa6db35 100644 --- a/tests/forecasts/timify/test_make_time_series.py +++ b/tests/forecasts/timify/test_make_time_series.py @@ -4,7 +4,7 @@ Unless otherwise noted, each `time_step` is 60 minutes long implying 12 time steps per day (i.e., we use `LONG_TIME_STEP` by default). """ -import datetime +import datetime as dt import pandas as pd import pytest @@ -20,7 +20,7 @@ def good_predict_at(): ... a long enough history so that either `SHORT_TRAIN_HORIZON` or `LONG_TRAIN_HORIZON` works. """ - return datetime.datetime( + return dt.datetime( test_config.END.year, test_config.END.month, test_config.END.day, @@ -36,8 +36,8 @@ def bad_predict_at(): ... not a long enough history so that both `SHORT_TRAIN_HORIZON` and `LONG_TRAIN_HORIZON` do not work. """ - predict_day = test_config.END - datetime.timedelta(weeks=6, days=1) - return datetime.datetime( + predict_day = test_config.END - dt.timedelta(weeks=6, days=1) + return dt.datetime( predict_day.year, predict_day.month, predict_day.day, @@ -341,7 +341,7 @@ class TestMakeRealTimeTimeSeries: The time series with the actual order counts always holds `1` value. """ - predict_at = datetime.datetime( + predict_at = dt.datetime( good_predict_at.year, good_predict_at.month, good_predict_at.day, From d00675219456a7b8971c8612a99eef2ebdccafba Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 17:09:39 +0100 Subject: [PATCH 10/21] Enforce the import conventions with `ruff` flake8 has no plugin with configurable aliases --- pyproject.toml | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 30e7b64..4345c8f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -333,10 +333,9 @@ multi_line_output = 3 use_parentheses = true # Comply with Google's Python Style Guide -# => All imports go on a single line except the ones from the typing module +# => All imports go on a single line # Source: https://google.github.io/styleguide/pyguide.html#313-imports-formatting force_single_line = true -single_line_exclusions = ["typing"] @@ -482,6 +481,8 @@ select = [ # ======================================= # eradicate => no commented-out code "ERA", + # flake8-import-conventions => Unified import aliases + "ICN", # isort => imports are sorted "I", # Pylint's refactoring rules => simpler and smaller functions @@ -531,13 +532,31 @@ parametrize-values-row-type = "tuple" parametrize-values-type = "list" +[tool.ruff.lint.flake8-import-conventions] + +# Import modules instead of objects from these modules +banned-from = [ + "collections.abc", + "nox.sessions", + "typing", +] + + +[tool.ruff.lint.flake8-import-conventions.extend-aliases] + +"collections.abc" = "cabc" +"sqlalchemy" = "sa" +"sqlalchemy.dialects.postgresql" = "psql" +"sqlalchemy.ext.hybrid" = "sa_hybrid" +"typing" = "t" + + [tool.ruff.lint.isort] # aligned with [tool.isort] above case-sensitive = false # Same as `isort` force-single-line = true lines-after-imports = 2 order-by-type = false -single-line-exclusions = ["typing"] [tool.ruff.lint.mccabe] From d660f0cc4ed6d9e62d0fe7c6d618322d57a1b049 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 19:53:15 +0100 Subject: [PATCH 11/21] Import `googlemaps` as `gm` everywhere --- pyproject.toml | 1 + tests/db/test_addresses_addresses.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4345c8f..ba2ea45 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -545,6 +545,7 @@ banned-from = [ [tool.ruff.lint.flake8-import-conventions.extend-aliases] "collections.abc" = "cabc" +"googlemaps" = "gm" "sqlalchemy" = "sa" "sqlalchemy.dialects.postgresql" = "psql" "sqlalchemy.ext.hybrid" = "sa_hybrid" diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index 087547f..7c34bf4 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -2,7 +2,7 @@ import json -import googlemaps +import googlemaps as gm import pytest import sqlalchemy as sa from geopy import distance @@ -635,7 +635,7 @@ class TestSyncWithGoogleMaps: def directions(_self, *_args, **_kwargs): return api_response - monkeypatch.setattr(googlemaps.Client, "directions", directions) + monkeypatch.setattr(gm.Client, "directions", directions) def test_sync_instances_with_google_maps(self, path): """Call the method for a `Path` object without Google data.""" From 07660ecff980932d082f82c43575fbfafc1172fe Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 19:55:34 +0100 Subject: [PATCH 12/21] Import `geopy.distance` as `geo_distance` everywhere --- pyproject.toml | 1 + tests/db/fake_data/factories/orders/ad_hoc.py | 4 ++-- tests/db/test_addresses_addresses.py | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index ba2ea45..da33d00 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -545,6 +545,7 @@ banned-from = [ [tool.ruff.lint.flake8-import-conventions.extend-aliases] "collections.abc" = "cabc" +"geopy.distance" = "geo_distance" "googlemaps" = "gm" "sqlalchemy" = "sa" "sqlalchemy.dialects.postgresql" = "psql" diff --git a/tests/db/fake_data/factories/orders/ad_hoc.py b/tests/db/fake_data/factories/orders/ad_hoc.py index e7632cb..02bd8a7 100644 --- a/tests/db/fake_data/factories/orders/ad_hoc.py +++ b/tests/db/fake_data/factories/orders/ad_hoc.py @@ -5,7 +5,7 @@ import random import factory from factory import alchemy -from geopy import distance +from geopy import distance as geo_distance from tests import config as test_config from tests.db.fake_data.factories import utils @@ -204,7 +204,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): # Statistical attributes -> calculate realistic stats logged_delivery_distance = factory.LazyAttribute( lambda obj: ( - distance.great_circle( + geo_distance.great_circle( (obj.pickup_address.latitude, obj.pickup_address.longitude), (obj.delivery_address.latitude, obj.delivery_address.longitude), ).meters diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index 7c34bf4..a9a0dbf 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -5,7 +5,7 @@ import json import googlemaps as gm import pytest import sqlalchemy as sa -from geopy import distance +from geopy import distance as geo_distance from sqlalchemy import exc as sa_exc from velofy import db @@ -21,7 +21,7 @@ def another_address(make_address): @pytest.fixture def path(address, another_address, make_address): """A `Path` from `address` to `another_address`.""" - air_distance = distance.great_circle( + air_distance = geo_distance.great_circle( address.location.lat_lng, another_address.location.lat_lng, ).meters From 07e90b7851e3c585270edf84b94fbb2998e51c46 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 19:56:58 +0100 Subject: [PATCH 13/21] Import `click.testing` as `cli_testing` Like `click.core` as `cli_core` --- pyproject.toml | 2 ++ tests/console/conftest.py | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index da33d00..34e32ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -544,6 +544,8 @@ banned-from = [ [tool.ruff.lint.flake8-import-conventions.extend-aliases] +"click.core" = "cli_core" +"click.testing" = "cli_testing" "collections.abc" = "cabc" "geopy.distance" = "geo_distance" "googlemaps" = "gm" diff --git a/tests/console/conftest.py b/tests/console/conftest.py index d6c2e59..30228db 100644 --- a/tests/console/conftest.py +++ b/tests/console/conftest.py @@ -1,10 +1,10 @@ """Fixture for testing the CLI scripts.""" import pytest -from click import testing as click_testing +from click import testing as cli_testing @pytest.fixture -def cli() -> click_testing.CliRunner: +def cli() -> cli_testing.CliRunner: """Initialize Click's CLI Test Runner.""" - return click_testing.CliRunner() + return cli_testing.CliRunner() From 9b844b16e777ef643ea20f93f9fe415ecc51ff20 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:03:25 +0100 Subject: [PATCH 14/21] Import `statsmodels.tsa.api` as `tsa` The alias in the `statsmodels` documentation --- pyproject.toml | 1 + src/velofy/forecasts/methods/extrapolate_season.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 34e32ad..30157e6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -552,6 +552,7 @@ banned-from = [ "sqlalchemy" = "sa" "sqlalchemy.dialects.postgresql" = "psql" "sqlalchemy.ext.hybrid" = "sa_hybrid" +"statsmodels.tsa.api" = "tsa" "typing" = "t" diff --git a/src/velofy/forecasts/methods/extrapolate_season.py b/src/velofy/forecasts/methods/extrapolate_season.py index a6ea8f6..7d70af7 100644 --- a/src/velofy/forecasts/methods/extrapolate_season.py +++ b/src/velofy/forecasts/methods/extrapolate_season.py @@ -1,7 +1,7 @@ """Forecast by linear extrapolation of a seasonal component.""" import pandas as pd -from statsmodels.tsa import api as ts_stats +from statsmodels.tsa import api as tsa def predict( @@ -46,7 +46,7 @@ def predict( # Obtain all `observations` of the same seasonal lag and # fit a straight line through them (= `trend`). observations = training_ts[slice(lag, 999_999_999, frequency)] - trend = observations - ts_stats.detrend(observations) + trend = observations - tsa.detrend(observations) # Create a point forecast by linear extrapolation # for one or even more time steps ahead. From 8bca30c83630a7136cba9c427d6bcc1dbffb2b7a Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:04:44 +0100 Subject: [PATCH 15/21] Import `rpy2.rinterface_lib.callbacks` as `r_callbacks` --- pyproject.toml | 1 + src/velofy/init_r.py | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 30157e6..db1ddb2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -549,6 +549,7 @@ banned-from = [ "collections.abc" = "cabc" "geopy.distance" = "geo_distance" "googlemaps" = "gm" +"rpy2.rinterface_lib.callbacks" = "r_callbacks" "sqlalchemy" = "sa" "sqlalchemy.dialects.postgresql" = "psql" "sqlalchemy.ext.hybrid" = "sa_hybrid" diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index 1c8bc46..ce95674 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -7,14 +7,14 @@ The Jupyter notebook "research/00_r_dependencies.ipynb" can be used to install a R dependencies on a Ubuntu/Debian based system. """ -from rpy2.rinterface_lib import callbacks as rcallbacks +from rpy2.rinterface_lib import callbacks as r_callbacks from rpy2.robjects import packages as rpackages # Suppress R's messages to stdout and stderr. # Source: https://stackoverflow.com/a/63220287 -rcallbacks.consolewrite_print = lambda *_args, **_kwargs: None # pragma: no cover -rcallbacks.consolewrite_warnerror = lambda *_args, **_kwargs: None # pragma: no cover +r_callbacks.consolewrite_print = lambda *_args, **_kwargs: None # pragma: no cover +r_callbacks.consolewrite_warnerror = lambda *_args, **_kwargs: None # pragma: no cover # For clarity and convenience, re-raise the error that results from missing R From e9743eaa013362cd4e79b19dd7dd0c25ede11e73 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:06:09 +0100 Subject: [PATCH 16/21] Import `rpy2.robjects.packages` as `r_packages` --- pyproject.toml | 1 + src/velofy/init_r.py | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index db1ddb2..1807eee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -550,6 +550,7 @@ banned-from = [ "geopy.distance" = "geo_distance" "googlemaps" = "gm" "rpy2.rinterface_lib.callbacks" = "r_callbacks" +"rpy2.robjects.packages" = "r_packages" "sqlalchemy" = "sa" "sqlalchemy.dialects.postgresql" = "psql" "sqlalchemy.ext.hybrid" = "sa_hybrid" diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index ce95674..eada0be 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -8,7 +8,7 @@ R dependencies on a Ubuntu/Debian based system. """ from rpy2.rinterface_lib import callbacks as r_callbacks -from rpy2.robjects import packages as rpackages +from rpy2.robjects import packages as r_packages # Suppress R's messages to stdout and stderr. @@ -20,9 +20,9 @@ r_callbacks.consolewrite_warnerror = lambda *_args, **_kwargs: None # pragma: n # For clarity and convenience, re-raise the error that results from missing R # dependencies with clearer instructions as to how to deal with it. try: - rpackages.importr("forecast") - rpackages.importr("zoo") + r_packages.importr("forecast") + r_packages.importr("zoo") -except rpackages.PackageNotInstalledError: # pragma: no cover +except r_packages.PackageNotInstalledError: # pragma: no cover msg = 'See the "research/00_r_dependencies.ipynb" notebook!' - raise rpackages.PackageNotInstalledError(msg) from None + raise r_packages.PackageNotInstalledError(msg) from None From dc45c689c40ccfe98c2148f9ba08612612121083 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:08:16 +0100 Subject: [PATCH 17/21] Import `alembic.command` as `alembic_cmd` --- pyproject.toml | 1 + tests/conftest.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 1807eee..0fce72f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -544,6 +544,7 @@ banned-from = [ [tool.ruff.lint.flake8-import-conventions.extend-aliases] +"alembic.command" = "alembic_cmd" "click.core" = "cli_core" "click.testing" = "cli_testing" "collections.abc" = "cabc" diff --git a/tests/conftest.py b/tests/conftest.py index ebd7fc8..5b1ac35 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,7 +8,7 @@ import os import pytest import sqlalchemy as sa -from alembic import command as migrations_cmd +from alembic import command as alembic_cmd from alembic import config as migrations_config from sqlalchemy import orm @@ -60,7 +60,7 @@ def db_connection(request): db.Base.metadata.create_all(connection) else: cfg = migrations_config.Config("alembic.ini") - migrations_cmd.upgrade(cfg, "head") + alembic_cmd.upgrade(cfg, "head") try: yield connection From de5e49b497cc8f5904637fa5d913e2f8b331f2e8 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:13:46 +0100 Subject: [PATCH 18/21] Import `alembic.config` as `alembic_config` --- pyproject.toml | 1 + tests/conftest.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0fce72f..db2cf8b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -545,6 +545,7 @@ banned-from = [ [tool.ruff.lint.flake8-import-conventions.extend-aliases] "alembic.command" = "alembic_cmd" +"alembic.config" = "alembic_config" "click.core" = "cli_core" "click.testing" = "cli_testing" "collections.abc" = "cabc" diff --git a/tests/conftest.py b/tests/conftest.py index 5b1ac35..2a89767 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,7 +9,7 @@ import os import pytest import sqlalchemy as sa from alembic import command as alembic_cmd -from alembic import config as migrations_config +from alembic import config as alembic_config from sqlalchemy import orm from velofy import config @@ -59,7 +59,7 @@ def db_connection(request): connection.execute(sa.text(f"CREATE SCHEMA {config.CLEAN_SCHEMA};")) db.Base.metadata.create_all(connection) else: - cfg = migrations_config.Config("alembic.ini") + cfg = alembic_config.Config("alembic.ini") alembic_cmd.upgrade(cfg, "head") try: From cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:19:35 +0100 Subject: [PATCH 19/21] Import `velofy.config` as `pkg_config` everywhere --- migrations/env.py | 12 ++-- pyproject.toml | 1 + src/velofy/console/forecasts.py | 16 ++--- src/velofy/console/gridify.py | 4 +- src/velofy/db/addresses.py | 4 +- src/velofy/db/addresses_addresses.py | 4 +- src/velofy/db/cities.py | 14 ++-- src/velofy/db/customers.py | 14 ++-- src/velofy/db/orders.py | 8 +-- src/velofy/db/pixels.py | 8 +-- src/velofy/db/restaurants.py | 12 ++-- src/velofy/forecasts/timify.py | 65 ++++++++++--------- tests/config.py | 6 +- tests/conftest.py | 16 +++-- tests/forecasts/conftest.py | 6 +- tests/forecasts/methods/test_predictions.py | 8 +-- .../forecasts/timify/test_make_time_series.py | 18 ++--- 17 files changed, 113 insertions(+), 103 deletions(-) diff --git a/migrations/env.py b/migrations/env.py index 49d1ac8..9613a00 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -6,7 +6,7 @@ from logging import config as log_config import sqlalchemy as sa from alembic import context -from velofy import config as velofy_config +from velofy import config as pkg_config from velofy import db @@ -24,7 +24,7 @@ def include_object(obj, _name, type_, _reflected, _compare_to): if ( type_ in {"table", "column"} and hasattr(obj, "schema") # => fix for rare edge case - and obj.schema != velofy_config.CLEAN_SCHEMA + and obj.schema != pkg_config.CLEAN_SCHEMA ): return False @@ -32,17 +32,17 @@ def include_object(obj, _name, type_, _reflected, _compare_to): # Without a `pool`, the `connection` really closes after the migrations -engine = sa.create_engine(velofy_config.DATABASE_URI, poolclass=sa.pool.NullPool) +engine = sa.create_engine(pkg_config.DATABASE_URI, poolclass=sa.pool.NullPool) -test_schema = f"_{velofy_config.CLEAN_SCHEMA}" if os.getenv("TESTING") else "" +test_schema = f"_{pkg_config.CLEAN_SCHEMA}" if os.getenv("TESTING") else "" with engine.connect() as connection: context.configure( connection=connection, include_object=include_object, target_metadata=db.Base.metadata, - version_table=f"{velofy_config.ALEMBIC_TABLE}{test_schema}", - version_table_schema=velofy_config.ALEMBIC_TABLE_SCHEMA, + version_table=f"{pkg_config.ALEMBIC_TABLE}{test_schema}", + version_table_schema=pkg_config.ALEMBIC_TABLE_SCHEMA, ) with context.begin_transaction(): diff --git a/pyproject.toml b/pyproject.toml index db2cf8b..f4d6232 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -558,6 +558,7 @@ banned-from = [ "sqlalchemy.ext.hybrid" = "sa_hybrid" "statsmodels.tsa.api" = "tsa" "typing" = "t" +"velofy.config" = "pkg_config" [tool.ruff.lint.isort] # aligned with [tool.isort] above diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index b8cb965..0c9f98d 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -12,7 +12,7 @@ import click import sqlalchemy as sa from sqlalchemy.orm import exc as orm_exc -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.console import decorators from velofy.forecasts import timify @@ -77,15 +77,15 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 if grid.side_length == side_length: break else: - click.echo(f"SIDE_LENGTH must be in {config.GRID_SIDE_LENGTHS}") + click.echo(f"SIDE_LENGTH must be in {pkg_config.GRID_SIDE_LENGTHS}") sys.exit(1) - if time_step not in config.TIME_STEPS: - click.echo(f"TIME_STEP must be in {config.TIME_STEPS}") + if time_step not in pkg_config.TIME_STEPS: + click.echo(f"TIME_STEP must be in {pkg_config.TIME_STEPS}") sys.exit(1) - if train_horizon not in config.TRAIN_HORIZONS: - click.echo(f"TRAIN_HORIZON must be in {config.TRAIN_HORIZONS}") + if train_horizon not in pkg_config.TRAIN_HORIZONS: + click.echo(f"TRAIN_HORIZON must be in {pkg_config.TRAIN_HORIZONS}") sys.exit(1) click.echo( @@ -140,9 +140,9 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 predict_day.year, predict_day.month, predict_day.day, - config.SERVICE_START, + pkg_config.SERVICE_START, ) - while predict_at.hour < config.SERVICE_END: + while predict_at.hour < pkg_config.SERVICE_END: model.make_forecast( pixel=pixel, predict_at=predict_at, diff --git a/src/velofy/console/gridify.py b/src/velofy/console/gridify.py index ea72bc5..4c82842 100644 --- a/src/velofy/console/gridify.py +++ b/src/velofy/console/gridify.py @@ -2,7 +2,7 @@ import click -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.console import decorators @@ -26,7 +26,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 for city in cities: click.echo(f"\nCreating grids for {city.name}") - for side_length in config.GRID_SIDE_LENGTHS: + for side_length in pkg_config.GRID_SIDE_LENGTHS: click.echo(f"Creating grid with a side length of {side_length} meters") grid = db.Grid.gridify(city=city, side_length=side_length) diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 34564a1..0c16f2c 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -12,7 +12,7 @@ from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql from sqlalchemy.ext import hybrid as sa_hybrid -from velofy import config +from velofy import config as pkg_config from velofy.db import meta from velofy.db import utils @@ -198,7 +198,7 @@ class Address(meta.Base): `.city.map` for convenience in interactive usage """ defaults: dict[str, t.Any] = { - "color": f"{config.NEUTRAL_COLOR}", + "color": f"{pkg_config.NEUTRAL_COLOR}", "popup": f"{self.street}, {self.zip_code} {self.city_name}", } defaults.update(kwargs) diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index ee5415d..1aeb4da 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -14,7 +14,7 @@ from geopy import distance as geo_distance from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.db import meta from velofy.db import utils @@ -219,7 +219,7 @@ class Path(meta.Base): if self.bicycle_distance is not None: return - client = gm.Client(config.GOOGLE_MAPS_API_KEY) + client = gm.Client(pkg_config.GOOGLE_MAPS_API_KEY) response = client.directions( origin=self.first_address.location.lat_lng, destination=self.second_address.location.lat_lng, diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 9fc9633..258add4 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -9,7 +9,7 @@ import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.db import meta from velofy.db import utils @@ -214,8 +214,8 @@ class City(meta.Base): address.draw( radius=radius, - color=config.RESTAURANT_COLOR, - fill_color=config.RESTAURANT_COLOR, + color=pkg_config.RESTAURANT_COLOR, + fill_color=pkg_config.RESTAURANT_COLOR, fill_opacity=0.3, tooltip=tooltip, ) @@ -223,7 +223,7 @@ class City(meta.Base): else: address.draw( radius=1, - color=config.RESTAURANT_COLOR, + color=pkg_config.RESTAURANT_COLOR, tooltip=tooltip, ) @@ -245,11 +245,11 @@ class City(meta.Base): sa.text( f""" SELECT DISTINCT - {config.CLEAN_SCHEMA}.addresses.zip_code + {pkg_config.CLEAN_SCHEMA}.addresses.zip_code FROM - {config.CLEAN_SCHEMA}.addresses AS addresses + {pkg_config.CLEAN_SCHEMA}.addresses AS addresses WHERE - {config.CLEAN_SCHEMA}.addresses.city_id = {self.id}; + {pkg_config.CLEAN_SCHEMA}.addresses.city_id = {self.id}; """, # noqa:S608 ), ) diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index aa400d2..b047b24 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -6,7 +6,7 @@ import folium import sqlalchemy as sa from sqlalchemy import orm -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.db import meta @@ -106,8 +106,8 @@ class Customer(meta.Base): address.draw( radius=radius, - color=config.CUSTOMER_COLOR, - fill_color=config.CUSTOMER_COLOR, + color=pkg_config.CUSTOMER_COLOR, + fill_color=pkg_config.CUSTOMER_COLOR, fill_opacity=0.3, tooltip=f"n_orders={n_orders}", ) @@ -115,7 +115,7 @@ class Customer(meta.Base): else: address.draw( radius=1, - color=config.CUSTOMER_COLOR, + color=pkg_config.CUSTOMER_COLOR, ) if restaurants: @@ -173,8 +173,8 @@ class Customer(meta.Base): address.draw( radius=radius, - color=config.RESTAURANT_COLOR, - fill_color=config.RESTAURANT_COLOR, + color=pkg_config.RESTAURANT_COLOR, + fill_color=pkg_config.RESTAURANT_COLOR, fill_opacity=0.3, tooltip=tooltip, ) @@ -182,7 +182,7 @@ class Customer(meta.Base): else: address.draw( radius=1, - color=config.RESTAURANT_COLOR, + color=pkg_config.RESTAURANT_COLOR, tooltip=tooltip, ) diff --git a/src/velofy/db/orders.py b/src/velofy/db/orders.py index 189d30a..91c66ff 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -7,7 +7,7 @@ import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.dialects import postgresql as psql -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.db import meta @@ -766,7 +766,7 @@ class Order(meta.Base): reverse=reverse, start_tooltip=start_tooltip, end_tooltip=end_tooltip, - start_color=config.RESTAURANT_COLOR, - end_color=config.CUSTOMER_COLOR, - path_color=config.NEUTRAL_COLOR, + start_color=pkg_config.RESTAURANT_COLOR, + end_color=pkg_config.CUSTOMER_COLOR, + path_color=pkg_config.NEUTRAL_COLOR, ) diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 61d155a..8c1b57b 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -9,7 +9,7 @@ import sqlalchemy as sa import utm from sqlalchemy import orm -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.db import meta from velofy.db import utils @@ -260,8 +260,8 @@ class Pixel(meta.Base): address.draw( radius=radius, - color=config.RESTAURANT_COLOR, - fill_color=config.RESTAURANT_COLOR, + color=pkg_config.RESTAURANT_COLOR, + fill_color=pkg_config.RESTAURANT_COLOR, fill_opacity=0.3, tooltip=tooltip, ) @@ -269,7 +269,7 @@ class Pixel(meta.Base): else: address.draw( radius=1, - color=config.RESTAURANT_COLOR, + color=pkg_config.RESTAURANT_COLOR, tooltip=tooltip, ) diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index db13cf6..bd4c467 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -8,7 +8,7 @@ import folium import sqlalchemy as sa from sqlalchemy import orm -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.db import meta @@ -151,8 +151,8 @@ class Restaurant(meta.Base): address.draw( radius=radius, - color=config.CUSTOMER_COLOR, - fill_color=config.CUSTOMER_COLOR, + color=pkg_config.CUSTOMER_COLOR, + fill_color=pkg_config.CUSTOMER_COLOR, fill_opacity=0.3, tooltip=f"n_orders={n_orders}", ) @@ -160,13 +160,13 @@ class Restaurant(meta.Base): else: address.draw( radius=1, - color=config.CUSTOMER_COLOR, + color=pkg_config.CUSTOMER_COLOR, ) self.address.draw( radius=20, - color=config.RESTAURANT_COLOR, - fill_color=config.RESTAURANT_COLOR, + color=pkg_config.RESTAURANT_COLOR, + fill_color=pkg_config.RESTAURANT_COLOR, fill_opacity=0.3, tooltip=f"{self.name} (#{self.id}) | n_orders={len(self.orders)}", ) diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index 457e0a5..a51ae67 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -7,7 +7,7 @@ import datetime as dt import pandas as pd import sqlalchemy as sa -from velofy import config +from velofy import config as pkg_config from velofy import db from velofy.forecasts import models @@ -34,7 +34,7 @@ class OrderHistory: # Number of daily time steps must be a whole multiple of `time_step` length. n_daily_time_steps = ( - 60 * (config.SERVICE_END - config.SERVICE_START) / time_step + 60 * (pkg_config.SERVICE_END - pkg_config.SERVICE_START) / time_step ) if n_daily_time_steps != int(n_daily_time_steps): # pragma: no cover raise RuntimeError("Internal error: configuration has invalid TIME_STEPS") @@ -96,37 +96,37 @@ class OrderHistory: ) AS minutes_to_be_cut FROM ( SELECT - {config.CLEAN_SCHEMA}.orders.id, - {config.CLEAN_SCHEMA}.orders.placed_at, - {config.CLEAN_SCHEMA}.orders.pickup_address_id + {pkg_config.CLEAN_SCHEMA}.orders.id, + {pkg_config.CLEAN_SCHEMA}.orders.placed_at, + {pkg_config.CLEAN_SCHEMA}.orders.pickup_address_id FROM - {config.CLEAN_SCHEMA}.orders + {pkg_config.CLEAN_SCHEMA}.orders INNER JOIN ( SELECT - {config.CLEAN_SCHEMA}.addresses.id AS address_id + {pkg_config.CLEAN_SCHEMA}.addresses.id AS address_id FROM - {config.CLEAN_SCHEMA}.addresses + {pkg_config.CLEAN_SCHEMA}.addresses WHERE - {config.CLEAN_SCHEMA}.addresses.city_id + {pkg_config.CLEAN_SCHEMA}.addresses.city_id = {self._grid.city.id} ) AS in_city - ON {config.CLEAN_SCHEMA}.orders.pickup_address_id + ON {pkg_config.CLEAN_SCHEMA}.orders.pickup_address_id = in_city.address_id WHERE - {config.CLEAN_SCHEMA}.orders.ad_hoc IS TRUE + {pkg_config.CLEAN_SCHEMA}.orders.ad_hoc IS TRUE ) AS orders INNER JOIN ( SELECT - {config.CLEAN_SCHEMA}.addresses_pixels.address_id, - {config.CLEAN_SCHEMA}.addresses_pixels.pixel_id + {pkg_config.CLEAN_SCHEMA}.addresses_pixels.address_id, + {pkg_config.CLEAN_SCHEMA}.addresses_pixels.pixel_id FROM - {config.CLEAN_SCHEMA}.addresses_pixels + {pkg_config.CLEAN_SCHEMA}.addresses_pixels WHERE - {config.CLEAN_SCHEMA}.addresses_pixels.grid_id + {pkg_config.CLEAN_SCHEMA}.addresses_pixels.grid_id = {self._grid.id} AND - {config.CLEAN_SCHEMA}.addresses_pixels.city_id + {pkg_config.CLEAN_SCHEMA}.addresses_pixels.city_id = {self._grid.city.id} -- -> sanity check ) AS pixels ON orders.pickup_address_id = pixels.address_id @@ -153,17 +153,22 @@ class OrderHistory: start_day.year, start_day.month, start_day.day, - config.SERVICE_START, + pkg_config.SERVICE_START, ) end_day = data.index.levels[1].max().date() - end = dt.datetime(end_day.year, end_day.month, end_day.day, config.SERVICE_END) + end = dt.datetime( + end_day.year, + end_day.month, + end_day.day, + pkg_config.SERVICE_END, + ) # ... and all possible `tuple`s of "pixel_id"-"start_at" combinations. # The "start_at" values must lie within the operating hours. gen = ( (pixel_id, start_at) for pixel_id in sorted(data.index.levels[0]) for start_at in pd.date_range(start, end, freq=f"{self._time_step}min") - if config.SERVICE_START <= start_at.hour < config.SERVICE_END + if pkg_config.SERVICE_START <= start_at.hour < pkg_config.SERVICE_END ) # Re-index `data` filling in `0`s where there is no demand. @@ -270,7 +275,7 @@ class OrderHistory: except KeyError: raise LookupError("The `pixel_id` is not in the `grid`") from None - if predict_at >= config.CUTOFF_DAY: # pragma: no cover + if predict_at >= pkg_config.CUTOFF_DAY: # pragma: no cover raise RuntimeError("Internal error: cannot predict beyond the given data") # The first and last training day are just before the `predict_at` day @@ -342,7 +347,7 @@ class OrderHistory: except KeyError: raise LookupError("The `pixel_id` is not in the `grid`") from None - if predict_day >= config.CUTOFF_DAY.date(): # pragma: no cover + if predict_day >= pkg_config.CUTOFF_DAY.date(): # pragma: no cover raise RuntimeError("Internal error: cannot predict beyond the given data") # The first and last training day are just before the `predict_day` @@ -352,7 +357,7 @@ class OrderHistory: first_train_day.year, first_train_day.month, first_train_day.day, - config.SERVICE_START, + pkg_config.SERVICE_START, 0, ) last_train_day = predict_day - dt.timedelta(days=1) @@ -360,7 +365,7 @@ class OrderHistory: last_train_day.year, last_train_day.month, last_train_day.day, - config.SERVICE_END, # subtract one `time_step` below + pkg_config.SERVICE_END, # subtract one `time_step` below 0, ) - dt.timedelta(minutes=self._time_step) @@ -379,14 +384,14 @@ class OrderHistory: predict_day.year, predict_day.month, predict_day.day, - config.SERVICE_START, + pkg_config.SERVICE_START, 0, ) last_prediction_at = dt.datetime( predict_day.year, predict_day.month, predict_day.day, - config.SERVICE_END, # subtract one `time_step` below + pkg_config.SERVICE_END, # subtract one `time_step` below 0, ) - dt.timedelta(minutes=self._time_step) @@ -431,7 +436,7 @@ class OrderHistory: except KeyError: raise LookupError("The `pixel_id` is not in the `grid`") from None - if predict_at >= config.CUTOFF_DAY: # pragma: no cover + if predict_at >= pkg_config.CUTOFF_DAY: # pragma: no cover raise RuntimeError("Internal error: cannot predict beyond the given data") # The first and last training day are just before the `predict_at` day @@ -442,16 +447,16 @@ class OrderHistory: first_train_day.year, first_train_day.month, first_train_day.day, - config.SERVICE_START, + pkg_config.SERVICE_START, 0, ) # Predicting the first time step on the `predict_at` day is a corner case. # Then, the previous day is indeed the `last_train_day`. Predicting any # other time step implies that the `predict_at` day is the `last_train_day`. # `last_train_time` is the last "start_at" before the one being predicted. - if predict_at.hour == config.SERVICE_START: + if predict_at.hour == pkg_config.SERVICE_START: last_train_day = predict_at.date() - dt.timedelta(days=1) - last_train_time = dt.time(config.SERVICE_END, 0) + last_train_time = dt.time(pkg_config.SERVICE_END, 0) else: last_train_day = predict_at.date() last_train_time = predict_at.time() @@ -479,7 +484,7 @@ class OrderHistory: predict_at.year, predict_at.month, predict_at.day, - config.SERVICE_START, + pkg_config.SERVICE_START, 0, ) ).seconds diff --git a/tests/config.py b/tests/config.py index 6f8ab74..9ee9a65 100644 --- a/tests/config.py +++ b/tests/config.py @@ -2,7 +2,7 @@ import datetime as dt -from velofy import config +from velofy import config as pkg_config # The day on which most test cases take place. @@ -15,9 +15,9 @@ NOON = 12 # `START` and `END` constitute a 57-day time span, 8 full weeks plus 1 day. # That implies a maximum `train_horizon` of `8` as that needs full 7-day weeks. -START = dt.datetime(YEAR, MONTH, DAY, config.SERVICE_START, 0) +START = dt.datetime(YEAR, MONTH, DAY, pkg_config.SERVICE_START, 0) _end = START + dt.timedelta(days=56) # `56` as `START` is not included -END = dt.datetime(_end.year, _end.month, _end.day, config.SERVICE_END, 0) +END = dt.datetime(_end.year, _end.month, _end.day, pkg_config.SERVICE_END, 0) # Default time steps (in minutes), for example, for `OrderHistory` objects. LONG_TIME_STEP = 60 diff --git a/tests/conftest.py b/tests/conftest.py index 2a89767..bdb2e70 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,7 +12,7 @@ from alembic import command as alembic_cmd from alembic import config as alembic_config from sqlalchemy import orm -from velofy import config +from velofy import config as pkg_config from velofy import db @@ -29,7 +29,7 @@ pytest_plugins = [ if not os.getenv("TESTING"): raise RuntimeError("Tests must be executed with TESTING set in the environment") -if not config.TESTING: +if not pkg_config.TESTING: raise RuntimeError("The testing configuration was not loaded") @@ -51,12 +51,12 @@ def db_connection(request): """ # We need a fresh database connection for each of the two `params`. # Otherwise, the first test of the parameter run second will fail. - engine = sa.create_engine(config.DATABASE_URI) + engine = sa.create_engine(pkg_config.DATABASE_URI) connection = engine.connect() if request.param == "all_at_once": with connection.begin(): - connection.execute(sa.text(f"CREATE SCHEMA {config.CLEAN_SCHEMA};")) + connection.execute(sa.text(f"CREATE SCHEMA {pkg_config.CLEAN_SCHEMA};")) db.Base.metadata.create_all(connection) else: cfg = alembic_config.Config("alembic.ini") @@ -71,13 +71,15 @@ def db_connection(request): connection.close() with engine.begin() as cleanup: - cleanup.execute(sa.text(f"DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;")) + cleanup.execute(sa.text(f"DROP SCHEMA {pkg_config.CLEAN_SCHEMA} CASCADE;")) if request.param == "sequentially": - tmp_alembic_version = f"{config.ALEMBIC_TABLE}_{config.CLEAN_SCHEMA}" + tmp_alembic_version = ( + f"{pkg_config.ALEMBIC_TABLE}_{pkg_config.CLEAN_SCHEMA}" + ) cleanup.execute( sa.text( - f"DROP TABLE {config.ALEMBIC_TABLE_SCHEMA}.{tmp_alembic_version};", # noqa:E501 + f"DROP TABLE {pkg_config.ALEMBIC_TABLE_SCHEMA}.{tmp_alembic_version};", # noqa:E501 ), ) diff --git a/tests/forecasts/conftest.py b/tests/forecasts/conftest.py index d5b6e3d..8378d33 100644 --- a/tests/forecasts/conftest.py +++ b/tests/forecasts/conftest.py @@ -6,7 +6,7 @@ import pandas as pd import pytest from tests import config as test_config -from velofy import config +from velofy import config as pkg_config from velofy.forecasts import timify @@ -57,7 +57,7 @@ def vertical_datetime_index(): gen = ( start_at for start_at in start_ats - if config.SERVICE_START <= start_at.hour < config.SERVICE_END + if pkg_config.SERVICE_START <= start_at.hour < pkg_config.SERVICE_END ) index = pd.Index(gen) @@ -113,7 +113,7 @@ def order_totals(good_pixel_id): (pixel_id, start_at) for pixel_id in pixel_ids for start_at in start_ats - if config.SERVICE_START <= start_at.hour < config.SERVICE_END + if pkg_config.SERVICE_START <= start_at.hour < pkg_config.SERVICE_END ) # Re-index `data` filling in `0`s where there is no demand. diff --git a/tests/forecasts/methods/test_predictions.py b/tests/forecasts/methods/test_predictions.py index 6dcf2ac..5681264 100644 --- a/tests/forecasts/methods/test_predictions.py +++ b/tests/forecasts/methods/test_predictions.py @@ -6,7 +6,7 @@ import pandas as pd import pytest from tests import config as test_config -from velofy import config +from velofy import config as pkg_config from velofy.forecasts.methods import arima from velofy.forecasts.methods import ets from velofy.forecasts.methods import extrapolate_season @@ -24,14 +24,14 @@ def forecast_interval(): future_day.year, future_day.month, future_day.day, - config.SERVICE_START, + pkg_config.SERVICE_START, 0, ) end_of_day = dt.datetime( future_day.year, future_day.month, future_day.day, - config.SERVICE_END, + pkg_config.SERVICE_END, 0, ) @@ -43,7 +43,7 @@ def forecast_interval(): gen = ( start_at for start_at in start_ats - if config.SERVICE_START <= start_at.hour < config.SERVICE_END + if pkg_config.SERVICE_START <= start_at.hour < pkg_config.SERVICE_END ) index = pd.Index(gen) diff --git a/tests/forecasts/timify/test_make_time_series.py b/tests/forecasts/timify/test_make_time_series.py index fa6db35..02ac158 100644 --- a/tests/forecasts/timify/test_make_time_series.py +++ b/tests/forecasts/timify/test_make_time_series.py @@ -10,7 +10,7 @@ import pandas as pd import pytest from tests import config as test_config -from velofy import config +from velofy import config as pkg_config @pytest.fixture @@ -221,7 +221,7 @@ class TestMakeVerticalTimeSeries: n_daily_time_steps = ( 60 - * (config.SERVICE_END - config.SERVICE_START) + * (pkg_config.SERVICE_END - pkg_config.SERVICE_START) // test_config.LONG_TIME_STEP ) @@ -247,7 +247,7 @@ class TestMakeVerticalTimeSeries: n_daily_time_steps = ( 60 - * (config.SERVICE_END - config.SERVICE_START) + * (pkg_config.SERVICE_END - pkg_config.SERVICE_START) // test_config.LONG_TIME_STEP ) @@ -345,7 +345,7 @@ class TestMakeRealTimeTimeSeries: good_predict_at.year, good_predict_at.month, good_predict_at.day, - config.SERVICE_START, + pkg_config.SERVICE_START, 0, ) result = order_history.make_realtime_ts( @@ -358,7 +358,7 @@ class TestMakeRealTimeTimeSeries: n_daily_time_steps = ( 60 - * (config.SERVICE_END - config.SERVICE_START) + * (pkg_config.SERVICE_END - pkg_config.SERVICE_START) // test_config.LONG_TIME_STEP ) @@ -395,11 +395,13 @@ class TestMakeRealTimeTimeSeries: n_daily_time_steps = ( 60 - * (config.SERVICE_END - config.SERVICE_START) + * (pkg_config.SERVICE_END - pkg_config.SERVICE_START) // test_config.LONG_TIME_STEP ) n_time_steps_before = ( - 60 * (test_config.NOON - config.SERVICE_START) // test_config.LONG_TIME_STEP + 60 + * (test_config.NOON - pkg_config.SERVICE_START) + // test_config.LONG_TIME_STEP ) assert ( @@ -427,7 +429,7 @@ class TestMakeRealTimeTimeSeries: n_daily_time_steps = ( 60 - * (config.SERVICE_END - config.SERVICE_START) + * (pkg_config.SERVICE_END - pkg_config.SERVICE_START) // test_config.LONG_TIME_STEP ) From 5c13d719cde9c183fcb181ae41f56a6db37cb111 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:21:43 +0100 Subject: [PATCH 20/21] Enforce the established import aliases with `ruff` These aliases were already in use before this branch --- pyproject.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index f4d6232..faa2744 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -551,12 +551,17 @@ banned-from = [ "collections.abc" = "cabc" "geopy.distance" = "geo_distance" "googlemaps" = "gm" +"logging.config" = "log_config" +"packaging.version" = "pkg_version" "rpy2.rinterface_lib.callbacks" = "r_callbacks" "rpy2.robjects.packages" = "r_packages" "sqlalchemy" = "sa" "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" "velofy.config" = "pkg_config" From 31dda815d95caa305d07af15d14ef62514a5d9b7 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Mon, 30 Nov 2026 20:25:54 +0100 Subject: [PATCH 21/21] Ignore the import renames in `git blame` --- .git-blame-ignore-revs | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index c957f76..53f16fb 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -3,3 +3,54 @@ # Use double quotes ea8f1a13e34bfce01ea66951311e5f5fb5ab967f + +# Use the `sa` alias for `sqlalchemy` everywhere +e30b3efbe8fc719f7d1d5bef32c69df67884f4d7 + +# Use `sa.func` instead of importing `func` +78e052b668d029204daeb17d0ded3938156f1f2b + +# Import the `postgresql` dialect as `psql` +9d3af5e44719c88e4115c429d38e9e795de5bf05 + +# Import `sqlalchemy.ext.hybrid` as `sa_hybrid` +0b2a1197a2b089120f66ae2c8c365fac983192f4 + +# Use builtin generics and `X | None` +c6518f6b39386a7c803d0c2792fdae6d61436064 + +# Import `typing` as `t` ... +9c3b52befb51f91026accb9d4d3e0874ef6c3d23 + +# Use the `nox` module import +f0c617955bc8e9d46cd4126e0a334f1a28cc7849 + +# Import `datetime` as `dt` everywhere +5ca16ae47c63c06ac67b11908f813a544c377670 + +# Import `googlemaps` as `gm` everywhere +d660f0cc4ed6d9e62d0fe7c6d618322d57a1b049 + +# Import `geopy.distance` as `geo_distance` everywhere +07660ecff980932d082f82c43575fbfafc1172fe + +# Import `click.testing` as `cli_testing` +07e90b7851e3c585270edf84b94fbb2998e51c46 + +# Import `statsmodels.tsa.api` as `tsa` +9b844b16e777ef643ea20f93f9fe415ecc51ff20 + +# Import `rpy2.rinterface_lib.callbacks` as `r_callbacks` +8bca30c83630a7136cba9c427d6bcc1dbffb2b7a + +# Import `rpy2.robjects.packages` as `r_packages` +e9743eaa013362cd4e79b19dd7dd0c25ede11e73 + +# Import `alembic.command` as `alembic_cmd` +dc45c689c40ccfe98c2148f9ba08612612121083 + +# Import `alembic.config` as `alembic_config` +de5e49b497cc8f5904637fa5d913e2f8b331f2e8 + +# Import `velofy.config` as `pkg_config` everywhere +cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3