Unify the way the imports work #9

Merged
alexander merged 21 commits from unify-imports into develop 2026-11-30 20:30:54 +01:00
49 changed files with 391 additions and 342 deletions

View file

@ -3,3 +3,54 @@
# Use double quotes # Use double quotes
ea8f1a13e34bfce01ea66951311e5f5fb5ab967f 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

View file

@ -6,7 +6,7 @@ from logging import config as log_config
import sqlalchemy as sa import sqlalchemy as sa
from alembic import context from alembic import context
from velofy import config as velofy_config from velofy import config as pkg_config
from velofy import db from velofy import db
@ -24,7 +24,7 @@ def include_object(obj, _name, type_, _reflected, _compare_to):
if ( if (
type_ in {"table", "column"} type_ in {"table", "column"}
and hasattr(obj, "schema") # => fix for rare edge case 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 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 # 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: with engine.connect() as connection:
context.configure( context.configure(
connection=connection, connection=connection,
include_object=include_object, include_object=include_object,
target_metadata=db.Base.metadata, target_metadata=db.Base.metadata,
version_table=f"{velofy_config.ALEMBIC_TABLE}{test_schema}", version_table=f"{pkg_config.ALEMBIC_TABLE}{test_schema}",
version_table_schema=velofy_config.ALEMBIC_TABLE_SCHEMA, version_table_schema=pkg_config.ALEMBIC_TABLE_SCHEMA,
) )
with context.begin_transaction(): with context.begin_transaction():

View file

@ -7,7 +7,7 @@ import os
import sqlalchemy as sa import sqlalchemy as sa
from alembic import op from alembic import op
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql as psql
from velofy import configuration from velofy import configuration
@ -29,12 +29,12 @@ def upgrade():
sa.Column("id", sa.SmallInteger(), autoincrement=False, nullable=False), sa.Column("id", sa.SmallInteger(), autoincrement=False, nullable=False),
sa.Column("name", sa.Unicode(length=10), nullable=False), sa.Column("name", sa.Unicode(length=10), nullable=False),
sa.Column("kml", sa.UnicodeText(), nullable=False), sa.Column("kml", sa.UnicodeText(), nullable=False),
sa.Column("center_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("center_latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("center_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("center_longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("northeast_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("northeast_latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("northeast_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("northeast_longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("southwest_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("southwest_latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("southwest_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("southwest_longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("initial_zoom", sa.SmallInteger(), nullable=False), sa.Column("initial_zoom", sa.SmallInteger(), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_cities")), 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("id", sa.Integer(), autoincrement=False, nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("vehicle", sa.Unicode(length=10), 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("capacity", sa.SmallInteger(), nullable=False),
sa.Column("pay_per_hour", sa.SmallInteger(), nullable=False), sa.Column("pay_per_hour", sa.SmallInteger(), nullable=False),
sa.Column("pay_per_order", 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("primary_id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("place_id", sa.Unicode(length=120), nullable=False), sa.Column("place_id", sa.Unicode(length=120), nullable=False),
sa.Column("latitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("longitude", postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("city_id", sa.SmallInteger(), nullable=False), sa.Column("city_id", sa.SmallInteger(), nullable=False),
sa.Column("city", sa.Unicode(length=25), nullable=False), sa.Column("city", sa.Unicode(length=25), nullable=False),
sa.Column("zip_code", sa.Integer(), 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("delivery_not_confirmed", sa.Boolean(), nullable=True),
sa.Column("courier_waited_at_delivery", 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_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.Column("logged_avg_speed_distance", sa.SmallInteger(), nullable=True),
sa.CheckConstraint( sa.CheckConstraint(
"0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900", "0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900",

View file

@ -8,7 +8,7 @@ import os
import sqlalchemy as sa import sqlalchemy as sa
from alembic import op from alembic import op
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql as psql
from velofy import configuration from velofy import configuration
@ -32,7 +32,7 @@ def upgrade():
sa.Column("time_step", sa.SmallInteger(), nullable=False), sa.Column("time_step", sa.SmallInteger(), nullable=False),
sa.Column("training_horizon", sa.SmallInteger(), nullable=False), sa.Column("training_horizon", sa.SmallInteger(), nullable=False),
sa.Column("method", sa.Unicode(length=20), 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.PrimaryKeyConstraint("id", name=op.f("pk_forecasts")),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
["pixel_id"], ["pixel_id"],

View file

@ -8,7 +8,7 @@ import os
import sqlalchemy as sa import sqlalchemy as sa
from alembic import op from alembic import op
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql as psql
from velofy import configuration from velofy import configuration
@ -32,22 +32,22 @@ def upgrade():
) )
op.add_column( op.add_column(
"forecasts", "forecasts",
sa.Column("low80", postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("low80", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
"forecasts", "forecasts",
sa.Column("high80", postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("high80", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
"forecasts", "forecasts",
sa.Column("low95", postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("low95", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
"forecasts", "forecasts",
sa.Column("high95", postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("high95", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_check_constraint( op.create_check_constraint(

View file

@ -8,7 +8,7 @@ import os
import sqlalchemy as sa import sqlalchemy as sa
from alembic import op from alembic import op
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql as psql
from velofy import configuration from velofy import configuration
@ -32,7 +32,7 @@ def upgrade():
sa.Column("air_distance", sa.Integer(), nullable=False), sa.Column("air_distance", sa.Integer(), nullable=False),
sa.Column("bicycle_distance", sa.Integer(), nullable=True), sa.Column("bicycle_distance", sa.Integer(), nullable=True),
sa.Column("bicycle_duration", 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( sa.PrimaryKeyConstraint(
"first_address_id", "first_address_id",
"second_address_id", "second_address_id",

View file

@ -23,19 +23,18 @@ e.g., `uv run nox -s test -- tests/test_config.py`.
""" """
import collections import collections
import collections.abc as cabc
import itertools import itertools
import os import os
import pathlib import pathlib
import tempfile import tempfile
from collections.abc import Mapping import typing as t
from typing import Any, Generator
import nox import nox
from nox.sessions import Session
from packaging import version as pkg_version 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. """Create a multi-level `defaultdict` with variable depth.
The returned `dict`ionary never raises a `KeyError` The returned `dict`ionary never raises a `KeyError`
@ -47,9 +46,9 @@ def nested_defaultdict() -> collections.defaultdict[str, Any]:
return collections.defaultdict(nested_defaultdict) 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.""" """Turn nested `dict`s into nested `defaultdict`s."""
if isinstance(obj, Mapping): if isinstance(obj, cabc.Mapping):
return collections.defaultdict( return collections.defaultdict(
nested_defaultdict, nested_defaultdict,
{key: defaultify(val) for key, val in obj.items()}, {key: defaultify(val) for key, val in obj.items()},
@ -57,7 +56,7 @@ def defaultify(obj: Any) -> Any:
return obj 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. """Load the contents of the pyproject.toml file.
The contents are represented as a `nested_defaultdict`; The contents are represented as a `nested_defaultdict`;
@ -140,7 +139,7 @@ os.makedirs(tempfile.tempdir, exist_ok=True)
@nox.session(name="format", python=MAIN_PYTHON) @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`. """Format source files with `autoflake`, `black`, `flynt`, `isort`, and `ruff`.
If no extra arguments are provided, all source files are formatted. 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) @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`. """Lint source files with `flake8`, `isort`, `mypy`, and `ruff`.
If no extra arguments are provided, all source files are linted. 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) @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`. """Run the unit and integration tests with `pytest`.
If no extra arguments are provided, the entire test suite 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) @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`. """Test the code snippets in the docstrings with `xdoctest`.
By default, all docstrings in the package are checked. 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) @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`. """Build the documentation with `sphinx`.
Also, verify that all external links work. 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") @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". """Set up the local develop environment in ".venv".
All dependency groups and extras are installed 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) @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`. """Check dependencies for vulnerabilities with `pip-audit`.
The dependencies are all those pinned in the uv.lock file. 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") @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. """Lock dependencies in pyproject.toml into uv.lock.
Convenience task to run after manual changes of dependencies 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") @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. """Pin dependencies in uv.lock to their latest MINOR/PATCH versions.
The allowed versions are the ranges in the pyproject.toml file. 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) @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. """Check the dependencies in uv.lock for upgrades.
This task checks if upgrades are available for the PyPI 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") @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`.""" """Install the `pre-commit` hooks and configure `git blame`."""
# .pre-commit-config.yaml sets the hook types via "default_install_hook_types" # .pre-commit-config.yaml sets the hook types via "default_install_hook_types"
session.run("uv", "run", "pre-commit", "install") 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") @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. """Remove (almost) all glob patterns listed in git's ignore file.
Compared to `git clean -X`, never remove local environment variables Compared to `git clean -X`, never remove local environment variables
@ -521,7 +520,7 @@ def clean_cwd(session: Session) -> None:
session.run("rm", "-rf", path) 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. """Expand glob patterns into (resolved) paths.
Args: Args:
@ -540,7 +539,7 @@ def _expand(*patterns: str) -> Generator[pathlib.Path, None, None]:
yield path.resolve() 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`.""" """Do not accept any `session.posargs`."""
if session.posargs: if session.posargs:
msg = 'be run without any positional arguments behind the "--"' 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}") 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.""" """Do not reuse a session with the "-r" or "-R" flags."""
if session._runner.venv._reused: if session._runner.venv._reused:
msg = 'be run without the "-r" and "-R" flags' 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}") session.warn(f"Should {msg}")
def start(session: Session) -> None: def start(session: nox.Session) -> None:
"""Show generic info about a session.""" """Show generic info about a session."""
if session.posargs: if session.posargs:
session.debug(f"Received extra arguments: {session.posargs}") session.debug(f"Received extra arguments: {session.posargs}")
@ -597,9 +596,9 @@ def start(session: Session) -> None:
def install_pinned( def install_pinned(
session: Session, session: nox.Session,
*packages_or_pip_args: str, *packages_or_pip_args: str,
**kwargs: Any, **kwargs: t.Any,
) -> None: ) -> None:
"""Install packages respecting the uv.lock file. """Install packages respecting the uv.lock file.
@ -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. """Installations may be skipped if a virtual environment can be reused.
Skipping package installations must be requested with the "-R" flag. Skipping package installations must be requested with the "-R" flag.

View file

@ -333,10 +333,9 @@ multi_line_output = 3
use_parentheses = true use_parentheses = true
# Comply with Google's Python Style Guide # 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 # Source: https://google.github.io/styleguide/pyguide.html#313-imports-formatting
force_single_line = true force_single_line = true
single_line_exclusions = ["typing"]
@ -482,6 +481,8 @@ select = [
# ======================================= # =======================================
# eradicate => no commented-out code # eradicate => no commented-out code
"ERA", "ERA",
# flake8-import-conventions => Unified import aliases
"ICN",
# isort => imports are sorted # isort => imports are sorted
"I", "I",
# Pylint's refactoring rules => simpler and smaller functions # Pylint's refactoring rules => simpler and smaller functions
@ -531,13 +532,46 @@ parametrize-values-row-type = "tuple"
parametrize-values-type = "list" 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]
"alembic.command" = "alembic_cmd"
"alembic.config" = "alembic_config"
"click.core" = "cli_core"
"click.testing" = "cli_testing"
"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"
[tool.ruff.lint.isort] # aligned with [tool.isort] above [tool.ruff.lint.isort] # aligned with [tool.isort] above
case-sensitive = false # Same as `isort` case-sensitive = false # Same as `isort`
force-single-line = true force-single-line = true
lines-after-imports = 2 lines-after-imports = 2
order-by-type = false order-by-type = false
single-line-exclusions = ["typing"]
[tool.ruff.lint.mccabe] [tool.ruff.lint.mccabe]

View file

@ -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. It is run as part of the "deps-upgrade-check" `nox` session.
""" """
import datetime import datetime as dt
import http.client import http.client
import json import json
import pathlib import pathlib
@ -77,9 +77,9 @@ def get_years_since_release(
latest_version = data["info"]["version"] latest_version = data["info"]["version"]
release_date = infos_for_pinned_release[0]["upload_time"] 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 return round(years_since_release, 1), latest_version
@ -116,7 +116,7 @@ def make_comment(
def write_report(lines: list[tuple[str, bool]]) -> None: def write_report(lines: list[tuple[str, bool]]) -> None:
"""Write all lines to the report file and the noteworthy ones to the CLI.""" """Write all lines to the report file and the noteworthy ones to the CLI."""
header = f""" header = f"""
# Created on: {datetime.date.today()} # Created on: {dt.date.today()}
# #
# The versions pinned in the uv.lock file are amended with information # The versions pinned in the uv.lock file are amended with information
# regarding the latest available version on PyPI and the no. of years # regarding the latest available version on PyPI and the no. of years

View file

@ -7,7 +7,7 @@ Within this package, use the `config` proxy at the package's top level
to access the current configuration! to access the current configuration!
""" """
import datetime import datetime as dt
import os import os
import random import random
import string import string
@ -28,11 +28,11 @@ class Config:
# ----------------------------- # -----------------------------
# Date after which the real-life data is discarded. # 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 # If a scheduled pre-order is made within this
# time horizon, we treat it as an ad-hoc order. # 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. # Operating hours of the platform.
SERVICE_START = 11 SERVICE_START = 11

View file

@ -1,24 +1,24 @@
"""Utils for the CLI scripts.""" """Utils for the CLI scripts."""
import collections.abc as cabc
import functools import functools
import os import os
import subprocess # noqa:S404 import subprocess # noqa:S404
import sys import sys
from typing import Any, Callable import typing as t
import click import click
def db_revision( def db_revision(rev: str) -> cabc.Callable[..., cabc.Callable[..., t.Any]]:
rev: str,
) -> Callable[..., Callable[..., Any]]: # pragma: no cover -> easy to check visually
"""A decorator ensuring the database is at a given revision.""" """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) @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.""" """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 result = subprocess.run( # noqa:S603,S607
["alembic", "current"], # noqa:S607 ["alembic", "current"], # noqa:S607
capture_output=True, capture_output=True,

View file

@ -9,10 +9,10 @@ import datetime as dt
import sys import sys
import click import click
from sqlalchemy import func import sqlalchemy as sa
from sqlalchemy.orm import exc as orm_exc 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 import db
from velofy.console import decorators from velofy.console import decorators
from velofy.forecasts import timify from velofy.forecasts import timify
@ -77,15 +77,15 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
if grid.side_length == side_length: if grid.side_length == side_length:
break break
else: 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) sys.exit(1)
if time_step not in config.TIME_STEPS: if time_step not in pkg_config.TIME_STEPS:
click.echo(f"TIME_STEP must be in {config.TIME_STEPS}") click.echo(f"TIME_STEP must be in {pkg_config.TIME_STEPS}")
sys.exit(1) sys.exit(1)
if train_horizon not in config.TRAIN_HORIZONS: if train_horizon not in pkg_config.TRAIN_HORIZONS:
click.echo(f"TRAIN_HORIZON must be in {config.TRAIN_HORIZONS}") click.echo(f"TRAIN_HORIZON must be in {pkg_config.TRAIN_HORIZONS}")
sys.exit(1) sys.exit(1)
click.echo( click.echo(
@ -105,7 +105,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
# commands are added the make `Forecast`s without the heuristic! # commands are added the make `Forecast`s without the heuristic!
# Continue with forecasting on the day the last prediction was made ... # Continue with forecasting on the day the last prediction was made ...
last_predict_at = ( 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.Pixel, db.Forecast.pixel_id == db.Pixel.id)
.join(db.Grid, db.Pixel.grid_id == db.Grid.id) .join(db.Grid, db.Pixel.grid_id == db.Grid.id)
.filter(db.Forecast.pixel == pixel) .filter(db.Forecast.pixel == pixel)
@ -140,9 +140,9 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
predict_day.year, predict_day.year,
predict_day.month, predict_day.month,
predict_day.day, 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( model.make_forecast(
pixel=pixel, pixel=pixel,
predict_at=predict_at, predict_at=predict_at,

View file

@ -2,7 +2,7 @@
import click import click
from velofy import config from velofy import config as pkg_config
from velofy import db from velofy import db
from velofy.console import decorators from velofy.console import decorators
@ -26,7 +26,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
for city in cities: for city in cities:
click.echo(f"\nCreating grids for {city.name}") 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") click.echo(f"Creating grid with a side length of {side_length} meters")
grid = db.Grid.gridify(city=city, side_length=side_length) grid = db.Grid.gridify(city=city, side_length=side_length)

View file

@ -1,6 +1,6 @@
"""The entry point for all CLI scripts in the project.""" """The entry point for all CLI scripts in the project."""
from typing import Any import typing as t
import click import click
from click import core as cli_core from click import core as cli_core
@ -8,7 +8,7 @@ from click import core as cli_core
import velofy 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.""" """Show the package's version."""
# If --version / -V is NOT passed in, # If --version / -V is NOT passed in,
# continue with the command. # continue with the command.

View file

@ -4,15 +4,15 @@ from __future__ import annotations
import datetime as dt import datetime as dt
import functools import functools
from typing import Any import typing as t
import folium import folium
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
from sqlalchemy.dialects import postgresql 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 import config as pkg_config
from velofy.db import meta from velofy.db import meta
from velofy.db import utils from velofy.db import utils
@ -43,11 +43,11 @@ class Address(meta.Base):
index=True, index=True,
) )
latitude: orm.Mapped[float] = orm.mapped_column( latitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
longitude: orm.Mapped[float] = orm.mapped_column( longitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
city_id: orm.Mapped[int] = orm.mapped_column( city_id: orm.Mapped[int] = orm.mapped_column(
@ -124,7 +124,7 @@ class Address(meta.Base):
"""Non-literal text representation.""" """Non-literal text representation."""
return f"<{self.__class__.__name__}({self.street} in {self.city_name})>" return f"<{self.__class__.__name__}({self.street} in {self.city_name})>"
@hybrid.hybrid_property @sa_hybrid.hybrid_property
def is_primary(self) -> bool: def is_primary(self) -> bool:
"""If an `Address` object is the earliest one entered at its location. """If an `Address` object is the earliest one entered at its location.
@ -185,7 +185,7 @@ class Address(meta.Base):
"""Shortcut to the `.city.map` object.""" """Shortcut to the `.city.map` object."""
return self.city.map 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`. """Draw the address on the `.city.map`.
By default, addresses are shown as black dots. By default, addresses are shown as black dots.
@ -197,8 +197,8 @@ class Address(meta.Base):
Returns: Returns:
`.city.map` for convenience in interactive usage `.city.map` for convenience in interactive usage
""" """
defaults: dict[str, Any] = { 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}", "popup": f"{self.street}, {self.zip_code} {self.city_name}",
} }
defaults.update(kwargs) defaults.update(kwargs)

View file

@ -5,7 +5,6 @@ from __future__ import annotations
import functools import functools
import itertools import itertools
import json import json
from typing import List, Tuple
import folium import folium
import googlemaps as gm import googlemaps as gm
@ -13,9 +12,9 @@ import ordered_set
import sqlalchemy as sa import sqlalchemy as sa
from geopy import distance as geo_distance from geopy import distance as geo_distance
from sqlalchemy import orm from sqlalchemy import orm
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql as psql
from velofy import config from velofy import config as pkg_config
from velofy import db from velofy import db
from velofy.db import meta from velofy.db import meta
from velofy.db import utils from velofy.db import utils
@ -68,7 +67,7 @@ class Path(meta.Base):
# An array of latitude-longitude pairs approximating a courier's way. # An array of latitude-longitude pairs approximating a courier's way.
_directions: orm.Mapped[str | None] = orm.mapped_column( _directions: orm.Mapped[str | None] = orm.mapped_column(
"directions", "directions",
postgresql.JSON, psql.JSON,
nullable=True, nullable=True,
) )
@ -127,7 +126,7 @@ class Path(meta.Base):
cls, cls,
*addresses: db.Address, *addresses: db.Address,
google_maps: bool = False, google_maps: bool = False,
) -> List[Path]: ) -> list[Path]:
"""Calculate pair-wise paths for `Address` objects. """Calculate pair-wise paths for `Address` objects.
This is the main constructor method for the class. This is the main constructor method for the class.
@ -220,7 +219,7 @@ class Path(meta.Base):
if self.bicycle_distance is not None: if self.bicycle_distance is not None:
return return
client = gm.Client(config.GOOGLE_MAPS_API_KEY) client = gm.Client(pkg_config.GOOGLE_MAPS_API_KEY)
response = client.directions( response = client.directions(
origin=self.first_address.location.lat_lng, origin=self.first_address.location.lat_lng,
destination=self.second_address.location.lat_lng, destination=self.second_address.location.lat_lng,
@ -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 # 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 # "end_location", we use an `OrderedSet` to find the unique latitude-longitude
# pairs that make up the path from `.first_address` to `.second_address`. # 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"]: for step in route["steps"]:
steps.add( steps.add(
(step["start_location"]["lat"], step["start_location"]["lng"]), (step["start_location"]["lat"], step["start_location"]["lng"]),
@ -262,7 +261,7 @@ class Path(meta.Base):
return self.first_address.city.map return self.first_address.city.map
@functools.cached_property @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 couriers' route from `.first_address` to `.second_address`.
The returned `Location`s all relate to `.first_address.city.southwest`. The returned `Location`s all relate to `.first_address.city.southwest`.

View file

@ -7,9 +7,9 @@ import functools
import folium import folium
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql as psql
from velofy import config from velofy import config as pkg_config
from velofy import db from velofy import db
from velofy.db import meta from velofy.db import meta
from velofy.db import utils from velofy.db import utils
@ -37,27 +37,27 @@ class City(meta.Base):
# Google Maps related columns # Google Maps related columns
center_latitude: orm.Mapped[float] = orm.mapped_column( center_latitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
center_longitude: orm.Mapped[float] = orm.mapped_column( center_longitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
northeast_latitude: orm.Mapped[float] = orm.mapped_column( northeast_latitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
northeast_longitude: orm.Mapped[float] = orm.mapped_column( northeast_longitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
southwest_latitude: orm.Mapped[float] = orm.mapped_column( southwest_latitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
southwest_longitude: orm.Mapped[float] = orm.mapped_column( southwest_longitude: orm.Mapped[float] = orm.mapped_column(
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
initial_zoom: orm.Mapped[int] = orm.mapped_column( initial_zoom: orm.Mapped[int] = orm.mapped_column(
@ -214,8 +214,8 @@ class City(meta.Base):
address.draw( address.draw(
radius=radius, radius=radius,
color=config.RESTAURANT_COLOR, color=pkg_config.RESTAURANT_COLOR,
fill_color=config.RESTAURANT_COLOR, fill_color=pkg_config.RESTAURANT_COLOR,
fill_opacity=0.3, fill_opacity=0.3,
tooltip=tooltip, tooltip=tooltip,
) )
@ -223,7 +223,7 @@ class City(meta.Base):
else: else:
address.draw( address.draw(
radius=1, radius=1,
color=config.RESTAURANT_COLOR, color=pkg_config.RESTAURANT_COLOR,
tooltip=tooltip, tooltip=tooltip,
) )
@ -245,11 +245,11 @@ class City(meta.Base):
sa.text( sa.text(
f""" f"""
SELECT DISTINCT SELECT DISTINCT
{config.CLEAN_SCHEMA}.addresses.zip_code {pkg_config.CLEAN_SCHEMA}.addresses.zip_code
FROM FROM
{config.CLEAN_SCHEMA}.addresses AS addresses {pkg_config.CLEAN_SCHEMA}.addresses AS addresses
WHERE WHERE
{config.CLEAN_SCHEMA}.addresses.city_id = {self.id}; {pkg_config.CLEAN_SCHEMA}.addresses.city_id = {self.id};
""", # noqa:S608 """, # noqa:S608
), ),
) )

View file

@ -8,7 +8,7 @@ That is the case on the CI server.
""" """
import os import os
from typing import cast import typing as t
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
@ -21,5 +21,5 @@ if os.getenv("TESTING"):
session: orm.Session = None # type: ignore[assignment] session: orm.Session = None # type: ignore[assignment]
else: # pragma: no cover 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) session = orm.Session(bind=engine)

View file

@ -4,7 +4,7 @@ import datetime as dt
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
from sqlalchemy.dialects import postgresql from sqlalchemy.dialects import postgresql as psql
from velofy.db import meta from velofy.db import meta
@ -30,7 +30,7 @@ class Courier(meta.Base):
) )
historic_speed: orm.Mapped[float] = orm.mapped_column( historic_speed: orm.Mapped[float] = orm.mapped_column(
"speed", "speed",
postgresql.DOUBLE_PRECISION, psql.DOUBLE_PRECISION,
nullable=False, nullable=False,
) )
capacity: orm.Mapped[int] = orm.mapped_column( capacity: orm.Mapped[int] = orm.mapped_column(

View file

@ -6,7 +6,7 @@ import folium
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
from velofy import config from velofy import config as pkg_config
from velofy import db from velofy import db
from velofy.db import meta from velofy.db import meta
@ -106,8 +106,8 @@ class Customer(meta.Base):
address.draw( address.draw(
radius=radius, radius=radius,
color=config.CUSTOMER_COLOR, color=pkg_config.CUSTOMER_COLOR,
fill_color=config.CUSTOMER_COLOR, fill_color=pkg_config.CUSTOMER_COLOR,
fill_opacity=0.3, fill_opacity=0.3,
tooltip=f"n_orders={n_orders}", tooltip=f"n_orders={n_orders}",
) )
@ -115,7 +115,7 @@ class Customer(meta.Base):
else: else:
address.draw( address.draw(
radius=1, radius=1,
color=config.CUSTOMER_COLOR, color=pkg_config.CUSTOMER_COLOR,
) )
if restaurants: if restaurants:
@ -173,8 +173,8 @@ class Customer(meta.Base):
address.draw( address.draw(
radius=radius, radius=radius,
color=config.RESTAURANT_COLOR, color=pkg_config.RESTAURANT_COLOR,
fill_color=config.RESTAURANT_COLOR, fill_color=pkg_config.RESTAURANT_COLOR,
fill_opacity=0.3, fill_opacity=0.3,
tooltip=tooltip, tooltip=tooltip,
) )
@ -182,7 +182,7 @@ class Customer(meta.Base):
else: else:
address.draw( address.draw(
radius=1, radius=1,
color=config.RESTAURANT_COLOR, color=pkg_config.RESTAURANT_COLOR,
tooltip=tooltip, tooltip=tooltip,
) )

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