Merge branch 'more-lint-rules' into develop
All checks were successful
CI / Checks (Python 3.13) (push) Successful in 1m53s

Reviewed-on: #10
This commit is contained in:
Alexander Hess 2026-11-30 23:59:08 +01:00 • committed by webartifex Forge
commit 927ea56082
Signed by: webartifex Forge
GPG key ID: FC460CAFCF91C88A
41 changed files with 692 additions and 252 deletions

View file

@ -54,3 +54,6 @@ de5e49b497cc8f5904637fa5d913e2f8b331f2e8
# Import `velofy.config` as `pkg_config` everywhere # Import `velofy.config` as `pkg_config` everywhere
cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3 cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3
# Capitalize the explanations after "=>"
0090145b654c098cc464aed757e6c1fdda7487bd

View file

@ -5,7 +5,7 @@ import velofy
project = velofy.__pkg_name__ project = velofy.__pkg_name__
author = velofy.__author__ author = velofy.__author__
copyright = f"2020, {author}" project_copyright = f"2020, {author}"
version = release = velofy.__version__ version = release = velofy.__version__
extensions = [ extensions = [

View file

@ -12,7 +12,8 @@ from velofy import db
# Disable the --sql option, a.k.a, the "offline mode". # Disable the --sql option, a.k.a, the "offline mode".
if context.is_offline_mode(): if context.is_offline_mode():
raise NotImplementedError("The --sql option is not implemented in this project") msg = "The --sql option is not implemented in this project"
raise NotImplementedError(msg)
# Set up the default Python logger from the alembic.ini file. # Set up the default Python logger from the alembic.ini file.
@ -21,14 +22,11 @@ log_config.fileConfig(context.config.config_file_name)
def include_object(obj, _name, type_, _reflected, _compare_to): def include_object(obj, _name, type_, _reflected, _compare_to):
"""Only include the clean schema into --autogenerate migrations.""" """Only include the clean schema into --autogenerate migrations."""
if ( return not (
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 != pkg_config.CLEAN_SCHEMA and obj.schema != pkg_config.CLEAN_SCHEMA
): )
return False
return True
# Without a `pool`, the `connection` really closes after the migrations # Without a `pool`, the `connection` really closes after the migrations

View file

@ -135,7 +135,7 @@ os.environ.setdefault("UV_PYTHON_PREFERENCE", "only-managed")
# Where to keep temporary files (e.g., the constraints file in `install_pinned()`) # Where to keep temporary files (e.g., the constraints file in `install_pinned()`)
tempfile.tempdir = ".cache/tmp" tempfile.tempdir = ".cache/tmp"
os.makedirs(tempfile.tempdir, exist_ok=True) pathlib.Path(tempfile.tempdir).mkdir(parents=True, exist_ok=True)
@nox.session(name="format", python=MAIN_PYTHON) @nox.session(name="format", python=MAIN_PYTHON)
@ -191,26 +191,40 @@ def lint_code(session: nox.Session) -> None:
# because otherwise it treats missing packages as `Any` # because otherwise it treats missing packages as `Any`
".", ".",
"flake8", "flake8",
"flake8-2020",
"flake8-annotations", "flake8-annotations",
"flake8-bandit", "flake8-bandit",
"flake8-black", "flake8-black",
"flake8-boolean-trap",
"flake8-broken-line", "flake8-broken-line",
"flake8-bugbear", "flake8-bugbear",
"flake8-builtins",
"flake8-commas", "flake8-commas",
"flake8-comprehensions", "flake8-comprehensions",
"flake8-debugger", "flake8-debugger",
"flake8-docstrings", "flake8-docstrings",
"flake8-errmsg",
"flake8-executable",
"flake8-implicit-str-concat",
"flake8-logging",
"flake8-pie",
"flake8-pyproject", "flake8-pyproject",
"flake8-pytest-style", "flake8-pytest-style",
"flake8-quotes", "flake8-quotes",
"flake8-raise",
"flake8-return",
"flake8-sfs", "flake8-sfs",
"flake8-simplify",
"flake8-tidy-imports",
"flake8-todos", "flake8-todos",
"flake8-unused-arguments", "flake8-unused-arguments",
"isort", "isort",
"mypy", "mypy",
"pandas-vet",
"pep8-naming", "pep8-naming",
"pydoclint[flake8]", "pydoclint[flake8]",
"ruff", "ruff",
"tryceratops",
) )
# Interpret extra arguments as `locations` of source files # Interpret extra arguments as `locations` of source files
@ -315,7 +329,7 @@ def build_docs(session: nox.Session) -> None:
# Verify that all external links return 200 OK # Verify that all external links return 200 OK
session.run("sphinx-build", "-b", "linkcheck", DOCS_LOCATION, DOCS_BUILD) session.run("sphinx-build", "-b", "linkcheck", DOCS_LOCATION, DOCS_BUILD)
session.log(f"Docs are available at {os.getcwd()}/{DOCS_BUILD}index.html") session.log(f"Docs are available at {pathlib.Path.cwd()}/{DOCS_BUILD}index.html")
@nox.session(name="venv", python=MAIN_PYTHON, venv_backend="none") @nox.session(name="venv", python=MAIN_PYTHON, venv_backend="none")
@ -520,7 +534,7 @@ def clean_cwd(session: nox.Session) -> None:
session.run("rm", "-rf", path) session.run("rm", "-rf", path)
def _expand(*patterns: str) -> cabc.Generator[pathlib.Path, None, None]: def _expand(*patterns: str) -> cabc.Generator[pathlib.Path]:
"""Expand glob patterns into (resolved) paths. """Expand glob patterns into (resolved) paths.
Args: Args:
@ -552,7 +566,7 @@ def do_not_accept_arguments(session: nox.Session, *, raise_error: bool = True) -
def do_not_reuse(session: nox.Session, *, raise_error: bool = True) -> None: 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: # noqa:SLF001
msg = 'be run without the "-r" and "-R" flags' msg = 'be run without the "-r" and "-R" flags'
if raise_error: if raise_error:
@ -640,10 +654,9 @@ def skip_install(session: nox.Session) -> bool:
""" """
# Same logic to skip package installation as in core `nox` # Same logic to skip package installation as in core `nox`
# See: https://github.com/wntrblm/nox/blob/2026.10.20/nox/sessions.py#L905 # See: https://github.com/wntrblm/nox/blob/2026.10.20/nox/sessions.py#L905
venv = session._runner.venv no_install = session._runner.global_config.no_install # noqa:SLF001
if session._runner.global_config.no_install and venv._reused: venv_reused = session._runner.venv._reused # noqa:SLF001
return True return bool(no_install and venv_reused)
return False
if MAIN_PYTHON not in SUPPORTED_PYTHONS: if MAIN_PYTHON not in SUPPORTED_PYTHONS:

View file

@ -91,25 +91,39 @@ dev = [
# Code Analyzers # Code Analyzers
"flake8 (>=7.5.0,<8.0.0)", "flake8 (>=7.5.0,<8.0.0)",
"flake8-2020 (>=1.8.1,<2.0.0)",
"flake8-annotations (>=3.3.1,<4.0.0)", "flake8-annotations (>=3.3.1,<4.0.0)",
"flake8-bandit (>=4.1.1,<5.0.0)", "flake8-bandit (>=4.1.1,<5.0.0)",
"flake8-black (>=0.5.0,<0.6.0)", "flake8-black (>=0.5.0,<0.6.0)",
"flake8-boolean-trap (>=1.0.1,<2.0.0)",
"flake8-broken-line (>=1.0.0,<2.0.0)", "flake8-broken-line (>=1.0.0,<2.0.0)",
"flake8-bugbear (>=26.11.22,<27.0.0)", "flake8-bugbear (>=26.11.22,<27.0.0)",
"flake8-builtins (>=3.2.0,<4.0.0)",
"flake8-commas (>=4.0.0,<5.0.0)", "flake8-commas (>=4.0.0,<5.0.0)",
"flake8-comprehensions (>=3.17.0,<4.0.0)", "flake8-comprehensions (>=3.17.0,<4.0.0)",
"flake8-debugger (>=4.1.2,<5.0.0)", "flake8-debugger (>=4.1.2,<5.0.0)",
"flake8-docstrings (>=1.7.0,<2.0.0)", "flake8-docstrings (>=1.7.0,<2.0.0)",
"flake8-errmsg (>=0.7.0,<0.8.0)",
"flake8-executable (>=2.1.3,<3.0.0)",
"flake8-implicit-str-concat (>=0.7.0,<0.8.0)",
"flake8-logging (>=1.8.0,<2.0.0)",
"flake8-pie (>=0.16.0,<0.17.0)",
"flake8-pyproject (>=1.2.4,<2.0.0)", "flake8-pyproject (>=1.2.4,<2.0.0)",
"flake8-pytest-style (>=2.2.0,<3.0.0)", "flake8-pytest-style (>=2.2.0,<3.0.0)",
"flake8-quotes (>=3.4.0,<4.0.0)", "flake8-quotes (>=3.4.0,<4.0.0)",
"flake8-raise (>=0.0.5,<0.1.0)",
"flake8-return (>=1.2.0,<2.0.0)",
"flake8-sfs (>=1.0.1,<2.0.0)", "flake8-sfs (>=1.0.1,<2.0.0)",
"flake8-simplify (>=0.31.1,<0.32.0)",
"flake8-tidy-imports (>=4.12.0,<5.0.0)",
"flake8-todos (>=0.3.1,<0.4.0)", "flake8-todos (>=0.3.1,<0.4.0)",
"flake8-unused-arguments (>=0.0.14,<0.1.0)", "flake8-unused-arguments (>=0.0.14,<0.1.0)",
"mypy (>=2.4.1,<3.0.0)", "mypy (>=2.4.1,<3.0.0)",
"pandas-vet (>=2023.8.2)",
"pep8-naming (>=0.15.1,<0.16.0)", "pep8-naming (>=0.15.1,<0.16.0)",
"pydoclint[flake8] (>=0.12.0,<0.13.0)", "pydoclint[flake8] (>=0.12.0,<0.13.0)",
"ruff (>=0.17.6,<0.18.0)", "ruff (>=0.17.6,<0.18.0)",
"tryceratops (>=2.4.1,<3.0.0)",
] ]
test = [ test = [
@ -190,47 +204,110 @@ select = [
# ============= # =============
# flake8's base # flake8's base
# ============= # =============
# mccabe => cyclomatic complexity # mccabe => Cyclomatic complexity
"C901", "C901",
# pycodestyle => PEP8 compliance # pycodestyle => PEP8 compliance
"E", "W", "E", "W",
# pyflakes => basic errors # pyflakes => Basic errors
"F4", "F5", "F6", "F7", "F8", "F9", "F4", "F5", "F6", "F7", "F8", "F9",
# ======= # =======
# plugins # plugins
# ======= # =======
# flake8-annotations => enforce type checking for functions # flake8-2020 => Correct `sys.version` checks
"YTT",
# flake8-annotations => Enforce type checking for functions
"ANN0", "ANN2", "ANN3", "ANN0", "ANN2", "ANN3",
# flake8-bandit => common security issues # flake8-bandit => Common security issues
"S1", "S2", "S3", "S4", "S5", "S6", "S7", "S1", "S2", "S3", "S4", "S5", "S6", "S7",
# flake8-black => complain if black would make changes # flake8-black => Complain if black would make changes
"BLK1", "BLK9", "BLK1", "BLK9",
# flake8-broken-line => no \ to end a line # flake8-boolean-trap => Keyword-only flags
"FBT",
# flake8-broken-line => No \ to end a line
"N400", "N400",
# flake8-bugbear => opinionated bugs and design flaws # flake8-bugbear => Opinionated bugs and design flaws
"B0", "B3", "B9", "B0", "B3", "B9",
# flake8-commas => better comma placements # flake8-builtins => No shadowing of builtins
"A0",
# flake8-commas => Better comma placements
"C8", "C8",
# flake8-comprehensions => better comprehensions # flake8-comprehensions => Better comprehensions
"C4", "C4",
# flake8-debugger => no debugger usage # flake8-debugger => No debugger usage
"T100", "T100",
# flake8-docstrings => PEP257 compliance # flake8-docstrings => PEP257 compliance
"D1", "D2", "D3", "D4", "D1", "D2", "D3", "D4",
# flake8-pytest-style => enforce a consistent style with pytest # flake8-errmsg => Shorter tracebacks
"EM",
# flake8-executable => Consistent shebangs and executable bits
"EXE",
# flake8-implicit-str-concat => Unified string concatenation
"ISC",
# flake8-logging => Correct use of `logging`
"LOG",
# flake8-pie => No unnecessary constructs
"PIE",
# flake8-pytest-style => Enforce a consistent style with pytest
"PT0", "PT0",
# flake8-quotes => use double quotes everywhere (complying with black) # flake8-quotes => Use double quotes everywhere (complying with black)
"Q0", "Q0",
# flake8-sfs => use f-strings as the only type of string formatting # flake8-raise => No parentheses for exceptions without arguments
"R1",
# flake8-return => Consistent return statements
"R5",
# flake8-sfs => Use f-strings as the only type of string formatting
"SFS", "SFS",
# flake8-todos => unify TODOs # flake8-simplify => Simpler code
"SIM",
# flake8-tidy-imports => No relative imports
"I25",
# flake8-todos => Unify TODOs
"T00", "T00",
# flake8-unused-arguments => declared function arguments must be used # flake8-unused-arguments => Declared function arguments must be used
"U100", "U100",
# pandas-vet => Idiomatic `pandas`
"PD0",
# pep8-naming => PEP8 naming conventions # pep8-naming => PEP8 naming conventions
"N8", "N8",
# pydoclint => docstring matches implementation # pydoclint => Docstring matches implementation
"DOC", "DOC",
# tryceratops => Clean exception handling
"TRY",
# ========================================
# `ruff` only (no working `flake8` plugin)
# ========================================
# flake8-blind-except => No blind `except Exception:`
# "BLE",
# eradicate => No commented-out code
# "ERA",
# flynt => F-strings instead of `str.join()`
# "FLY",
# refurb => Modern idioms
# "FURB",
# flake8-logging-format => Lazy `logging` messages
# "G",
# isort => Imports are sorted
# "I",
# flake8-import-conventions => Unified import aliases
# "ICN",
# NumPy-specific rules => Modern `numpy` APIs
# "NPY",
# Perflint => No performance anti-patterns
# "PERF",
# pygrep-hooks => Specific "# noqa" and "# type: ignore" comments
# "PGH",
# Pylint => Fewer bugs and simpler code
# "PL",
# flake8-use-pathlib => `pathlib` instead of `os` functions
# "PTH",
# Ruff-specific rules => Fewer bugs and cleaner code
# "RUF",
# flake8-self => No access to private members from outside
# "SLF",
# flake8-print => No `print()`
# "T20",
# pyupgrade => Modern syntax for the targeted Python version
# "UP",
] ]
# By default, flake8 ignores some errors. # By default, flake8 ignores some errors.
@ -240,19 +317,35 @@ ignore = []
# If --ignore is passed on the command # If --ignore is passed on the command
# line, still ignore the following: # line, still ignore the following:
extend-ignore = [ extend-ignore = [
# Too long line => duplicate with E501. # `ruff`'s A003 does this better, as it only flags actual shadowing
"A003",
# Too long line => Duplicate with E501.
"B950", "B950",
# PEP 257 documents the arguments of `__init__()` in its own docstring. # PEP 257 documents the arguments of `__init__()` in its own docstring.
"DOC301", "DOC301",
# Comply with black's style. # Comply with black's style.
# Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 # Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8
"E203", "W503", "E203", "W503",
# `ruff`'s FBT003 does this better, as it allows builtins like `setattr()`.
"FBT003",
# Every `.add()` looks like `pandas` to this rule (`ruff` omits it).
"PD005",
# `len()` is needed for `pandas` objects, as their truth value is ambiguous.
"PIE787",
# Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`. # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`.
"PT023", "PT023",
# `ruff`'s RET504 does this better, as it allows statements in between.
"R504",
# An `elif` after a `return` keeps a case distinction together.
"R505",
# Allow f-strings as the only type of string formatting. # Allow f-strings as the only type of string formatting.
"SFS301", "SFS301",
# `bool()` around a comparison can be deliberate (`ruff` omits this rule).
"SIM901",
# TODOs need neither an author nor an issue. # TODOs need neither an author nor an issue.
"T002", "T003", "T002", "T003",
# Messages are written where the exceptions are raised.
"TRY003",
] ]
per-file-ignores = [ per-file-ignores = [
@ -446,49 +539,108 @@ select = [
# =================================== # ===================================
# Violations also covered by `flake8` # Violations also covered by `flake8`
# =================================== # ===================================
# flake8-annotations => enforce type checking for functions # flake8-builtins => No shadowing of builtins
"A",
# flake8-annotations => Enforce type checking for functions
"ANN0", "ANN2", "ANN0", "ANN2",
# flake8-unused-arguments ("U100") => declared function arguments must be used # flake8-unused-arguments ("U100") => Declared function arguments must be used
"ARG", "ARG",
# flake8-bugbear => opinionated bugs and design flaws # flake8-bugbear => Opinionated bugs and design flaws
"B", "B",
# flake8-comprehensions => better comprehensions # flake8-comprehensions => Better comprehensions
"C4", "C4",
# mccabe => cyclomatic complexity # mccabe => Cyclomatic complexity
"C90", "C90",
# flake8-commas ("C8") => better comma placements # flake8-commas ("C8") => Better comma placements
"COM", "COM",
# flake8-docstrings => PEP257 compliance # flake8-docstrings => PEP257 compliance
"D", "D",
# pycodestyle => PEP8 compliance # pycodestyle => PEP8 compliance
"E", "W", "E", "W",
# pyflakes => basic errors # flake8-errmsg => Shorter tracebacks
"EM",
# flake8-executable => Consistent shebangs and executable bits
"EXE",
# pyflakes => Basic errors
"F", "F",
# flake8-boolean-trap => Keyword-only flags
"FBT",
# flake8-implicit-str-concat => Unified string concatenation
"ISC",
# flake8-logging => Correct use of `logging`
"LOG",
# pep8-naming => PEP8 naming conventions # pep8-naming => PEP8 naming conventions
"N", "N",
# flake8-pytest-style => enforce a consistent style with pytest # pandas-vet => Idiomatic `pandas`
"PD",
# flake8-pie => No unnecessary constructs
"PIE",
# flake8-pytest-style => Enforce a consistent style with pytest
"PT", "PT",
# flake8-quotes => use double quotes everywhere # flake8-quotes => Use double quotes everywhere
"Q", "Q",
# flake8-bandit => common security issues # flake8-return ("R5") => Consistent return statements
"RET",
# flake8-raise ("R1") => No parentheses for exceptions without arguments
"RSE",
# flake8-bandit => Common security issues
"S", "S",
# flake8-debugger => no debugger usage # flake8-simplify => Simpler code
"SIM",
# flake8-debugger => No debugger usage
"T10", "T10",
# flake8-todos => unify TODOs # flake8-todos => Unify TODOs
"TD", "TD",
# flake8-tidy-imports ("I25") => No relative imports
"TID",
# tryceratops => Clean exception handling
"TRY",
# flake8-2020 => Correct `sys.version` checks
"YTT",
# ======================================= # =======================================
# Violations not covered by `flake8` above # Violations not covered by `flake8` above
# ======================================= # =======================================
# eradicate => no commented-out code # flake8-blind-except => No blind `except Exception:`
"BLE",
# eradicate => No commented-out code
"ERA", "ERA",
# flynt => F-strings instead of `str.join()`
"FLY",
# refurb => Modern idioms
"FURB",
# isort => Imports are sorted
"I",
# flake8-import-conventions => Unified import aliases # flake8-import-conventions => Unified import aliases
"ICN", "ICN",
# isort => imports are sorted # NumPy-specific rules => Modern `numpy` APIs
"I", "NPY",
# Pylint's refactoring rules => simpler and smaller functions # Perflint => No performance anti-patterns
"PLR", "PERF",
# flake8-print => no `print()` # pygrep-hooks => Specific "# noqa" and "# type: ignore" comments
"PGH",
# Pylint => Fewer bugs and simpler code
"PL",
# flake8-use-pathlib => `pathlib` instead of `os` functions
"PTH",
# Ruff-specific rules => Fewer bugs and cleaner code
"RUF",
# flake8-self => No access to private members from outside
"SLF",
# flake8-print => No `print()`
"T20", "T20",
# pyupgrade => Modern syntax for the targeted Python version
"UP",
# =====================================
# `flake8` only (no `ruff` counterpart)
# =====================================
# flake8-black => Complain if black would make changes
# "BLK",
# pydoclint => Docstring matches implementation
# "DOC",
# flake8-broken-line => No \ to end a line
# "N400",
# flake8-sfs => Use f-strings as the only type of string formatting
# "SFS",
] ]
extend-ignore = [ extend-ignore = [
@ -498,8 +650,21 @@ extend-ignore = [
"PLR2004", "PLR2004",
# Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`. # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`.
"PT023", "PT023",
# An `elif` after a `return` keeps a case distinction together.
"RET505",
# Some "# noqa" comments are only for `flake8`, which `ruff` cannot know.
"RUF100",
# TODOs need neither an author nor an issue. # TODOs need neither an author nor an issue.
"TD002", "TD003", "TD002", "TD003",
# Messages are written where the exceptions are raised.
"TRY003",
]
# Codes only `flake8` knows, kept in "# noqa" comments
external = [
"B902",
"DOC",
] ]
@ -521,7 +686,8 @@ extend-ignore = [
# - PLR0913, PLR0917 => `pytest` passes fixtures as arguments. # - PLR0913, PLR0917 => `pytest` passes fixtures as arguments.
# - S101 => `assert` statements are ok in the test suite. # - S101 => `assert` statements are ok in the test suite.
# - S311 => The `random` module is not used for cryptography. # - S311 => The `random` module is not used for cryptography.
"tests/**/*.py" = ["ANN0", "ANN2", "D106", "PLR0913", "PLR0917", "S101", "S311"] # - SLF001 => Tests may set up and inspect private members.
"tests/**/*.py" = ["ANN0", "ANN2", "D106", "PLR0913", "PLR0917", "S101", "S311", "SLF001"]
[tool.ruff.lint.flake8-pytest-style] # aligned with [tool.flake8] above [tool.ruff.lint.flake8-pytest-style] # aligned with [tool.flake8] above

View file

@ -108,7 +108,7 @@
" -> created 38 pixels\n", " -> created 38 pixels\n",
"Creating grid with a side length of 1414 meters\n", "Creating grid with a side length of 1414 meters\n",
" -> created 24 pixels\n", " -> created 24 pixels\n",
"=> assigned 358 out of 48058 addresses in Lyon\n", "=> Assigned 358 out of 48058 addresses in Lyon\n",
"\n", "\n",
"Creating grids for Paris\n", "Creating grids for Paris\n",
"Creating grid with a side length of 707 meters\n", "Creating grid with a side length of 707 meters\n",
@ -117,7 +117,7 @@
" -> created 111 pixels\n", " -> created 111 pixels\n",
"Creating grid with a side length of 1414 meters\n", "Creating grid with a side length of 1414 meters\n",
" -> created 66 pixels\n", " -> created 66 pixels\n",
"=> assigned 1133 out of 108135 addresses in Paris\n", "=> Assigned 1133 out of 108135 addresses in Paris\n",
"\n", "\n",
"Creating grids for Bordeaux\n", "Creating grids for Bordeaux\n",
"Creating grid with a side length of 707 meters\n", "Creating grid with a side length of 707 meters\n",
@ -126,7 +126,7 @@
" -> created 22 pixels\n", " -> created 22 pixels\n",
"Creating grid with a side length of 1414 meters\n", "Creating grid with a side length of 1414 meters\n",
" -> created 15 pixels\n", " -> created 15 pixels\n",
"=> assigned 123 out of 21742 addresses in Bordeaux\n" "=> Assigned 123 out of 21742 addresses in Bordeaux\n"
] ]
} }
], ],

View file

@ -77,7 +77,7 @@ 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 = dt.datetime.fromisoformat(release_date.replace("Z", "+00:00")) release_date = dt.datetime.fromisoformat(release_date)
years_since_release = (dt.datetime.now() - release_date).days / 365.25 years_since_release = (dt.datetime.now() - release_date).days / 365.25
@ -100,10 +100,7 @@ def make_comment(
is_latest = pinned_version == latest_version is_latest = pinned_version == latest_version
if is_latest: comment = "up-to-date" if is_latest else f"< {latest_version:<8}"
comment = "up-to-date"
else:
comment = f"< {latest_version:<8}"
if years_since_release > PKG_CONSIDERED_OLD: if years_since_release > PKG_CONSIDERED_OLD:
comment += f" {years_since_release} years ago" comment += f" {years_since_release} years ago"

View file

@ -40,19 +40,19 @@ class Config:
# Side lengths (in meters) for which pixel grids are created. # Side lengths (in meters) for which pixel grids are created.
# They are the basis for the aggregated demand forecasts. # They are the basis for the aggregated demand forecasts.
GRID_SIDE_LENGTHS = [707, 1000, 1414] GRID_SIDE_LENGTHS = (707, 1000, 1414)
# Time steps (in minutes) used to aggregate the # Time steps (in minutes) used to aggregate the
# individual orders into time series. # individual orders into time series.
TIME_STEPS = [60] TIME_STEPS = (60,)
# Training horizons (in full weeks) used to train the forecasting models. # Training horizons (in full weeks) used to train the forecasting models.
# For now, we only use 7 and 8 weeks as that was the best performing in # For now, we only use 7 and 8 weeks as that was the best performing in
# a previous study (note:4f79e8fa). # a previous study (note:4f79e8fa).
TRAIN_HORIZONS = [7, 8] TRAIN_HORIZONS = (7, 8)
# The demand forecasting methods used in the simulations. # The demand forecasting methods used in the simulations.
FORECASTING_METHODS = ["hets", "rtarima"] FORECASTING_METHODS = ("hets", "rtarima")
# Colors for the visualizations ins `folium`. # Colors for the visualizations ins `folium`.
RESTAURANT_COLOR = "red" RESTAURANT_COLOR = "red"
@ -115,7 +115,8 @@ def make_config(env: str = "production") -> Config:
elif env.strip().lower() == "testing": elif env.strip().lower() == "testing":
config = TestingConfig() config = TestingConfig()
else: else:
raise ValueError("Must be either 'production' or 'testing'") msg = "Must be either 'production' or 'testing'"
raise ValueError(msg)
# Without a PostgreSQL database the package cannot work. # Without a PostgreSQL database the package cannot work.
# As pytest sets the "TESTING" environment variable explicitly, # As pytest sets the "TESTING" environment variable explicitly,

View file

@ -64,7 +64,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
TIME_STEP: length of one time step in minutes; defaults to `60` TIME_STEP: length of one time step in minutes; defaults to `60`
TRAIN_HORIZON: length of the training horizon; defaults to `8` TRAIN_HORIZON: length of the training horizon; defaults to `8`
""" # noqa:D412,D417 => formatted as `click` help text """ # noqa:D412,D417 => Formatted as `click` help text
# Input validation. # Input validation.
try: try:
@ -90,8 +90,8 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
click.echo( click.echo(
"Parameters: " "Parameters: "
+ f"city={city}, grid.side_length={side_length}, " f"city={city}, grid.side_length={side_length}, "
+ f"time_step={time_step}, train_horizon={train_horizon}", f"time_step={time_step}, train_horizon={train_horizon}",
) )
# Load the historic order data. # Load the historic order data.
@ -132,7 +132,7 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
) )
click.echo( click.echo(
f"Predicting pixel #{pixel.id} in {city} " f"Predicting pixel #{pixel.id} in {city} "
+ f"for {predict_day} with {model.name}", f"for {predict_day} with {model.name}",
) )
# Only loop over the time steps corresponding to working hours. # Only loop over the time steps corresponding to working hours.

View file

@ -42,7 +42,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
.count() .count()
) )
click.echo( click.echo(
f"=> assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501 f"=> Assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501
) )
db.session.commit() db.session.commit()

View file

@ -8,7 +8,12 @@ from click import core as cli_core
import velofy import velofy
def show_version(ctx: cli_core.Context, _param: t.Any, value: bool) -> None: def show_version(
ctx: cli_core.Context,
_param: t.Any,
# `click` passes all arguments to callbacks positionally
value: bool, # noqa:FBT001
) -> 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

@ -147,9 +147,9 @@ class Path(meta.Base):
paths = [] paths = []
# We consider all 2-tuples of `Address`es. The symmetric graph is ... # We consider all 2-tuples of `Address`es. The symmetric graph is ...
for first, second in itertools.combinations(addresses, 2): for pair in itertools.combinations(addresses, 2):
# ... implicitly enforced by a precedence constraint for the `.id`s. # ... implicitly enforced by a precedence constraint for the `.id`s.
first, second = (first, second) if first.id < second.id else (second, first) first, second = sorted(pair, key=lambda address: address.id)
# If there is no `Path` object in the database ... # If there is no `Path` object in the database ...
path = ( path = (
@ -183,7 +183,7 @@ class Path(meta.Base):
return paths return paths
@classmethod @classmethod
def from_order(cls, order: db.Order, google_maps: bool = False) -> Path: def from_order(cls, order: db.Order, *, google_maps: bool = False) -> Path:
"""Calculate the path for an `Order` object. """Calculate the path for an `Order` object.
The path goes from the `Order.pickup_address` to the `Order.delivery_address`. The path goes from the `Order.pickup_address` to the `Order.delivery_address`.
@ -270,7 +270,8 @@ class Path(meta.Base):
underlying attributes (i.e., `._directions`) are to be changed. underlying attributes (i.e., `._directions`) are to be changed.
""" """
if not self._directions: if not self._directions:
raise RuntimeError("_directions is not set") msg = "_directions is not set"
raise RuntimeError(msg)
points = [utils.Location(*point) for point in json.loads(self._directions)] points = [utils.Location(*point) for point in json.loads(self._directions)]
for point in points: for point in points:

View file

@ -149,6 +149,7 @@ class City(meta.Base):
def draw_restaurants( def draw_restaurants(
self, self,
*,
order_counts: bool = False, # pragma: no cover order_counts: bool = False, # pragma: no cover
) -> folium.Map: ) -> folium.Map:
"""Draw all restaurants on the`.map`. """Draw all restaurants on the`.map`.

View file

@ -46,6 +46,7 @@ class Customer(meta.Base):
def draw( # noqa:C901,PLR0912 def draw( # noqa:C901,PLR0912
self, self,
*,
restaurants: bool = True, restaurants: bool = True,
order_counts: bool = False, # pragma: no cover order_counts: bool = False, # pragma: no cover
) -> folium.Map: ) -> folium.Map:

View file

@ -232,25 +232,13 @@ class Forecast(meta.Base):
low95 = data.loc[timestamp_idx, "low95"] low95 = data.loc[timestamp_idx, "low95"]
high95 = data.loc[timestamp_idx, "high95"] high95 = data.loc[timestamp_idx, "high95"]
if math.isnan(low80): low80 = None if math.isnan(low80) else float(round(low80, 5))
low80 = None
else:
low80 = float(round(low80, 5))
if math.isnan(high80): high80 = None if math.isnan(high80) else float(round(high80, 5))
high80 = None
else:
high80 = float(round(high80, 5))
if math.isnan(low95): low95 = None if math.isnan(low95) else float(round(low95, 5))
low95 = None
else:
low95 = float(round(low95, 5))
if math.isnan(high95): high95 = None if math.isnan(high95) else float(round(high95, 5))
high95 = None
else:
high95 = float(round(high95, 5))
forecasts.append( forecasts.append(
cls( cls(

View file

@ -528,7 +528,7 @@ class Order(meta.Base):
def corrected(self) -> bool: def corrected(self) -> bool:
"""If any timestamp was corrected as compared to the original data.""" """If any timestamp was corrected as compared to the original data."""
return bool( return bool(
self.scheduled_delivery_at_corrected # => too much logic self.scheduled_delivery_at_corrected # => Too much logic
or self.cancelled_at_corrected or self.cancelled_at_corrected
or self.restaurant_notified_at_corrected or self.restaurant_notified_at_corrected
or self.restaurant_confirmed_at_corrected or self.restaurant_confirmed_at_corrected
@ -549,9 +549,11 @@ class Order(meta.Base):
This measures the time it took the UDP to notify the `.courier` after dispatch. This measures the time it took the UDP to notify the `.courier` after dispatch.
""" """
if not self.dispatch_at: if not self.dispatch_at:
raise RuntimeError("dispatch_at is not set") msg = "dispatch_at is not set"
raise RuntimeError(msg)
if not self.courier_accepted_at: if not self.courier_accepted_at:
raise RuntimeError("courier_accepted_at is not set") msg = "courier_accepted_at is not set"
raise RuntimeError(msg)
return self.courier_accepted_at - self.dispatch_at return self.courier_accepted_at - self.dispatch_at
@property @property
@ -561,36 +563,44 @@ class Order(meta.Base):
A subset of `.time_to_accept`. A subset of `.time_to_accept`.
""" """
if not self.courier_notified_at: if not self.courier_notified_at:
raise RuntimeError("courier_notified_at is not set") msg = "courier_notified_at is not set"
raise RuntimeError(msg)
if not self.courier_accepted_at: if not self.courier_accepted_at:
raise RuntimeError("courier_accepted_at is not set") msg = "courier_accepted_at is not set"
raise RuntimeError(msg)
return self.courier_accepted_at - self.courier_notified_at return self.courier_accepted_at - self.courier_notified_at
@property @property
def time_to_pickup(self) -> dt.timedelta: def time_to_pickup(self) -> dt.timedelta:
"""Time from the `.courier`'s acceptance to arrival at `.pickup_address`.""" """Time from the `.courier`'s acceptance to arrival at `.pickup_address`."""
if not self.courier_accepted_at: if not self.courier_accepted_at:
raise RuntimeError("courier_accepted_at is not set") msg = "courier_accepted_at is not set"
raise RuntimeError(msg)
if not self.reached_pickup_at: if not self.reached_pickup_at:
raise RuntimeError("reached_pickup_at is not set") msg = "reached_pickup_at is not set"
raise RuntimeError(msg)
return self.reached_pickup_at - self.courier_accepted_at return self.reached_pickup_at - self.courier_accepted_at
@property @property
def time_at_pickup(self) -> dt.timedelta: def time_at_pickup(self) -> dt.timedelta:
"""Time the `.courier` stayed at the `.pickup_address`.""" """Time the `.courier` stayed at the `.pickup_address`."""
if not self.reached_pickup_at: if not self.reached_pickup_at:
raise RuntimeError("reached_pickup_at is not set") msg = "reached_pickup_at is not set"
raise RuntimeError(msg)
if not self.pickup_at: if not self.pickup_at:
raise RuntimeError("pickup_at is not set") msg = "pickup_at is not set"
raise RuntimeError(msg)
return self.pickup_at - self.reached_pickup_at return self.pickup_at - self.reached_pickup_at
@property @property
def scheduled_pickup_at(self) -> dt.datetime: def scheduled_pickup_at(self) -> dt.datetime:
"""Point in time at which the pickup was scheduled.""" """Point in time at which the pickup was scheduled."""
if not self.restaurant_notified_at: if not self.restaurant_notified_at:
raise RuntimeError("restaurant_notified_at is not set") msg = "restaurant_notified_at is not set"
raise RuntimeError(msg)
if not self.estimated_prep_duration: if not self.estimated_prep_duration:
raise RuntimeError("estimated_prep_duration is not set") msg = "estimated_prep_duration is not set"
raise RuntimeError(msg)
delta = dt.timedelta(seconds=self.estimated_prep_duration) delta = dt.timedelta(seconds=self.estimated_prep_duration)
return self.restaurant_notified_at + delta return self.restaurant_notified_at + delta
@ -605,7 +615,8 @@ class Order(meta.Base):
Goes together with `.courier_late`. Goes together with `.courier_late`.
""" """
if not self.reached_pickup_at: if not self.reached_pickup_at:
raise RuntimeError("reached_pickup_at is not set") msg = "reached_pickup_at is not set"
raise RuntimeError(msg)
return max( return max(
dt.timedelta(), dt.timedelta(),
@ -623,7 +634,8 @@ class Order(meta.Base):
Goes together with `.courier_early`. Goes together with `.courier_early`.
""" """
if not self.reached_pickup_at: if not self.reached_pickup_at:
raise RuntimeError("reached_pickup_at is not set") msg = "reached_pickup_at is not set"
raise RuntimeError(msg)
return max( return max(
dt.timedelta(), dt.timedelta(),
@ -641,7 +653,8 @@ class Order(meta.Base):
Goes together with `.restaurant_late`. Goes together with `.restaurant_late`.
""" """
if not self.pickup_at: if not self.pickup_at:
raise RuntimeError("pickup_at is not set") msg = "pickup_at is not set"
raise RuntimeError(msg)
return max(dt.timedelta(), self.scheduled_pickup_at - self.pickup_at) return max(dt.timedelta(), self.scheduled_pickup_at - self.pickup_at)
@ -656,7 +669,8 @@ class Order(meta.Base):
Goes together with `.restaurant_early`. Goes together with `.restaurant_early`.
""" """
if not self.pickup_at: if not self.pickup_at:
raise RuntimeError("pickup_at is not set") msg = "pickup_at is not set"
raise RuntimeError(msg)
return max(dt.timedelta(), self.pickup_at - self.scheduled_pickup_at) return max(dt.timedelta(), self.pickup_at - self.scheduled_pickup_at)
@ -664,18 +678,22 @@ class Order(meta.Base):
def time_to_delivery(self) -> dt.timedelta: def time_to_delivery(self) -> dt.timedelta:
"""Time the `.courier` took from `.pickup_address` to `.delivery_address`.""" """Time the `.courier` took from `.pickup_address` to `.delivery_address`."""
if not self.pickup_at: if not self.pickup_at:
raise RuntimeError("pickup_at is not set") msg = "pickup_at is not set"
raise RuntimeError(msg)
if not self.reached_delivery_at: if not self.reached_delivery_at:
raise RuntimeError("reached_delivery_at is not set") msg = "reached_delivery_at is not set"
raise RuntimeError(msg)
return self.reached_delivery_at - self.pickup_at return self.reached_delivery_at - self.pickup_at
@property @property
def time_at_delivery(self) -> dt.timedelta: def time_at_delivery(self) -> dt.timedelta:
"""Time the `.courier` stayed at the `.delivery_address`.""" """Time the `.courier` stayed at the `.delivery_address`."""
if not self.reached_delivery_at: if not self.reached_delivery_at:
raise RuntimeError("reached_delivery_at is not set") msg = "reached_delivery_at is not set"
raise RuntimeError(msg)
if not self.delivery_at: if not self.delivery_at:
raise RuntimeError("delivery_at is not set") msg = "delivery_at is not set"
raise RuntimeError(msg)
return self.delivery_at - self.reached_delivery_at return self.delivery_at - self.reached_delivery_at
@property @property
@ -696,11 +714,14 @@ class Order(meta.Base):
Goes together with `.delivery_late`. Goes together with `.delivery_late`.
""" """
if not self.scheduled: if not self.scheduled:
raise AttributeError("Makes sense only for scheduled orders") msg = "Makes sense only for scheduled orders"
raise AttributeError(msg)
if not self.scheduled_delivery_at: if not self.scheduled_delivery_at:
raise RuntimeError("scheduled_delivery_at is not set") msg = "scheduled_delivery_at is not set"
raise RuntimeError(msg)
if not self.delivery_at: if not self.delivery_at:
raise RuntimeError("delivery_at is not set") msg = "delivery_at is not set"
raise RuntimeError(msg)
return max(dt.timedelta(), self.scheduled_delivery_at - self.delivery_at) return max(dt.timedelta(), self.scheduled_delivery_at - self.delivery_at)
@property @property
@ -714,22 +735,28 @@ class Order(meta.Base):
Goes together with `.delivery_early`. Goes together with `.delivery_early`.
""" """
if not self.scheduled: if not self.scheduled:
raise AttributeError("Makes sense only for scheduled orders") msg = "Makes sense only for scheduled orders"
raise AttributeError(msg)
if not self.scheduled_delivery_at: if not self.scheduled_delivery_at:
raise RuntimeError("scheduled_delivery_at is not set") msg = "scheduled_delivery_at is not set"
raise RuntimeError(msg)
if not self.delivery_at: if not self.delivery_at:
raise RuntimeError("delivery_at is not set") msg = "delivery_at is not set"
raise RuntimeError(msg)
return max(dt.timedelta(), self.delivery_at - self.scheduled_delivery_at) return max(dt.timedelta(), self.delivery_at - self.scheduled_delivery_at)
@property @property
def total_time(self) -> dt.timedelta: def total_time(self) -> dt.timedelta:
"""Time from order placement to delivery for an `.ad_hoc` order.""" """Time from order placement to delivery for an `.ad_hoc` order."""
if self.scheduled: if self.scheduled:
raise AttributeError("Scheduled orders have no total_time") msg = "Scheduled orders have no total_time"
raise AttributeError(msg)
if self.cancelled: if self.cancelled:
raise RuntimeError("Cancelled orders have no total_time") msg = "Cancelled orders have no total_time"
raise RuntimeError(msg)
if not self.delivery_at: if not self.delivery_at:
raise RuntimeError("delivery_at is not set") msg = "delivery_at is not set"
raise RuntimeError(msg)
return self.delivery_at - self.placed_at return self.delivery_at - self.placed_at
# Other Methods # Other Methods

View file

@ -156,8 +156,9 @@ class Pixel(meta.Base):
"""Shortcut to the `.city.map` object.""" """Shortcut to the `.city.map` object."""
return self.grid.city.map return self.grid.city.map
def draw( # noqa:C901,PLR0912 def draw(
self, self,
*,
restaurants: bool = True, restaurants: bool = True,
order_counts: bool = False, # pragma: no cover order_counts: bool = False, # pragma: no cover
) -> folium.Map: ) -> folium.Map:
@ -177,10 +178,7 @@ class Pixel(meta.Base):
info_text = f"Pixel({self.n_x}|{self.n_y})" info_text = f"Pixel({self.n_x}|{self.n_y})"
# Make the `Pixel`s look like a checkerboard. # Make the `Pixel`s look like a checkerboard.
if (self.n_x + self.n_y) % 2: color = "#808000" if (self.n_x + self.n_y) % 2 else "#ff8c00"
color = "#808000"
else:
color = "#ff8c00"
marker = folium.Rectangle( marker = folium.Rectangle(
bounds=bounds, bounds=bounds,

View file

@ -91,6 +91,7 @@ class Restaurant(meta.Base):
def draw( def draw(
self, self,
*,
customers: bool = True, customers: bool = True,
order_counts: bool = False, # pragma: no cover order_counts: bool = False, # pragma: no cover
) -> folium.Map: ) -> folium.Map:

View file

@ -8,6 +8,7 @@ from matplotlib import colors
def make_random_cmap( def make_random_cmap(
n_colors: int, n_colors: int,
*,
bright: bool = True, # pragma: no cover bright: bool = True, # pragma: no cover
) -> colors.LinearSegmentedColormap: ) -> colors.LinearSegmentedColormap:
"""Create a random `Colormap` with `n_colors` different colors. """Create a random `Colormap` with `n_colors` different colors.
@ -19,21 +20,19 @@ def make_random_cmap(
Returns: Returns:
colormap colormap
""" """
np.random.seed(42) rng = np.random.default_rng(42)
if bright: if bright:
hsv_colors = [ hsv_colors = [
( (
np.random.uniform(low=0.0, high=1), rng.uniform(low=0.0, high=1),
np.random.uniform(low=0.2, high=1), rng.uniform(low=0.2, high=1),
np.random.uniform(low=0.9, high=1), rng.uniform(low=0.9, high=1),
) )
for _ in range(n_colors) for _ in range(n_colors)
] ]
rgb_colors = [] rgb_colors = [colorsys.hsv_to_rgb(*color) for color in hsv_colors]
for color in hsv_colors:
rgb_colors.append(colorsys.hsv_to_rgb(*color))
else: else:
low = 0.0 low = 0.0
@ -41,9 +40,9 @@ def make_random_cmap(
rgb_colors = [ rgb_colors = [
( (
np.random.uniform(low=low, high=high), rng.uniform(low=low, high=high),
np.random.uniform(low=low, high=high), rng.uniform(low=low, high=high),
np.random.uniform(low=low, high=high), rng.uniform(low=low, high=high),
) )
for _ in range(n_colors) for _ in range(n_colors)
] ]

View file

@ -94,13 +94,17 @@ class Location:
"""The UTM zone of the location as the zone number and the band.""" """The UTM zone of the location as the zone number and the band."""
return self._zone, self._band return self._zone, self._band
# Explicitly unhashable, the default for classes defining only `__eq__()`
__hash__ = None # type: ignore[assignment]
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:
"""Check if two `Location` objects are the same location.""" """Check if two `Location` objects are the same location."""
if not isinstance(other, Location): if not isinstance(other, Location):
return NotImplemented return NotImplemented
if self.zone != other.zone: if self.zone != other.zone:
raise ValueError("locations must be in the same zone, including the band") msg = "locations must be in the same zone, including the band"
raise ValueError(msg)
return (self.easting, self.northing) == (other.easting, other.northing) return (self.easting, self.northing) == (other.easting, other.northing)
@ -111,7 +115,8 @@ class Location:
The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`. The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`.
""" """
if self._normalized_easting is None: if self._normalized_easting is None:
raise RuntimeError("an origin to relate to must be set first") msg = "an origin to relate to must be set first"
raise RuntimeError(msg)
return self._normalized_easting return self._normalized_easting
@ -122,7 +127,8 @@ class Location:
The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`. The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`.
""" """
if self._normalized_northing is None: if self._normalized_northing is None:
raise RuntimeError("an origin to relate to must be set first") msg = "an origin to relate to must be set first"
raise RuntimeError(msg)
return self._normalized_northing return self._normalized_northing
@ -137,13 +143,16 @@ class Location:
properties, the `other` origin may only be set once! properties, the `other` origin may only be set once!
""" """
if self._normalized_easting is not None: if self._normalized_easting is not None:
raise RuntimeError("the `other` origin may only be set once") msg = "the `other` origin may only be set once"
raise RuntimeError(msg)
if not isinstance(other, Location): if not isinstance(other, Location):
raise TypeError("`other` is not a `Location` object") msg = "`other` is not a `Location` object"
raise TypeError(msg)
if self.zone != other.zone: if self.zone != other.zone:
raise ValueError("`other` must be in the same zone, including the band") msg = "`other` must be in the same zone, including the band"
raise ValueError(msg)
self._normalized_easting = self.easting - other.easting self._normalized_easting = self.easting - other.easting
self._normalized_northing = self.northing - other.northing self._normalized_northing = self.northing - other.northing

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