Skip to content

Commit

Permalink
MNT: target py39 as new minimum, enable pyupgrade for ruff, bump min …
Browse files Browse the repository at this point in the history
…dependencie versions (#614)
  • Loading branch information
theOehrly committed Jul 24, 2024
1 parent c56b044 commit f768b9f
Show file tree
Hide file tree
Showing 29 changed files with 95 additions and 141 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/selective_cache_persist.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [ '3.8-minver', '3.8', '3.9', '3.10', '3.11', '3.12']
python-version: [ '3.9-minver', '3.9', '3.10', '3.11', '3.12']
#
name: Persist cache for ${{ matrix.python-version }}
steps:
Expand Down
3 changes: 1 addition & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ jobs:
matrix:
include:
- name-suffix: "(Minimum Versions)"
python-version: "3.8"
python-version: "3.9"
cache-suffix: "-minver"
extra-requirements: "-c requirements/minver.txt"
- python-version: "3.8"
- python-version: "3.9"
- python-version: "3.10"
- python-version: "3.11"
Expand Down
9 changes: 4 additions & 5 deletions fastf1/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import json
import zlib
from typing import (
Dict,
Optional,
Union
)
Expand All @@ -29,15 +28,15 @@

base_url = 'https://livetiming.formula1.com'

headers: Dict[str, str] = {
headers: dict[str, str] = {
'Host': 'livetiming.formula1.com',
'Connection': 'close',
'TE': 'identity',
'User-Agent': 'BestHTTP',
'Accept-Encoding': 'gzip, identity',
}

pages: Dict[str, str] = {
pages: dict[str, str] = {
'session_data': 'SessionData.json', # track + session status + lap count
'session_info': 'SessionInfo.jsonStream', # more rnd
'archive_status': 'ArchiveStatus.json', # rnd=1880327548
Expand Down Expand Up @@ -83,7 +82,7 @@ def make_path(wname, wdate, sname, sdate):


# define all empty columns for timing data
EMPTY_LAPS = {'Time': pd.NaT, 'Driver': str(), 'LapTime': pd.NaT,
EMPTY_LAPS = {'Time': pd.NaT, 'Driver': '', 'LapTime': pd.NaT,
'NumberOfLaps': np.nan, 'NumberOfPitStops': np.nan,
'PitOutTime': pd.NaT, 'PitInTime': pd.NaT,
'Sector1Time': pd.NaT, 'Sector2Time': pd.NaT,
Expand All @@ -92,7 +91,7 @@ def make_path(wname, wdate, sname, sdate):
'SpeedI1': np.nan, 'SpeedI2': np.nan, 'SpeedFL': np.nan,
'SpeedST': np.nan, 'IsPersonalBest': False}

EMPTY_STREAM = {'Time': pd.NaT, 'Driver': str(), 'Position': np.nan,
EMPTY_STREAM = {'Time': pd.NaT, 'Driver': '', 'Position': np.nan,
'GapToLeader': np.nan, 'IntervalToPositionAhead': np.nan}


Expand Down
23 changes: 9 additions & 14 deletions fastf1/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,13 @@
import re
import typing
import warnings
from collections.abc import Iterable
from functools import cached_property
from typing import (
Any,
Callable,
Iterable,
List,
Literal,
Optional,
Tuple,
Union
)

Expand Down Expand Up @@ -925,8 +923,8 @@ def add_driver_ahead(self, drop_existing: bool = True) -> "Telemetry":
)

if ((d['Date'].shape != dtd['Date'].shape)
or np.any((d['Date'].values
!= dtd['Date'].values))):
or np.any(d['Date'].values
!= dtd['Date'].values)):
dtd = dtd.resample_channels(new_date_ref=d["Date"])

# indices need to match as .join works index-on-index
Expand Down Expand Up @@ -1510,7 +1508,7 @@ def _load_laps_data(self, livedata=None):
elif not len(d2):
result = d1.copy()
result.reset_index(drop=True, inplace=True)
result['Compound'] = str()
result['Compound'] = ''
result['TyreLife'] = np.nan
result['Stint'] = 0
result['New'] = False
Expand Down Expand Up @@ -3295,7 +3293,7 @@ def pick_accurate(self) -> "Laps":
"""
return self[self['IsAccurate']]

def split_qualifying_sessions(self) -> List[Optional["Laps"]]:
def split_qualifying_sessions(self) -> list[Optional["Laps"]]:
"""Splits a lap object into individual laps objects for each
qualifying session.
Expand Down Expand Up @@ -3354,7 +3352,7 @@ def split_qualifying_sessions(self) -> List[Optional["Laps"]]:
return laps

def iterlaps(self, require: Optional[Iterable] = None) \
-> Iterable[Tuple[int, "Lap"]]:
-> Iterable[tuple[int, "Lap"]]:
"""Iterator for iterating over all laps in self.
This method wraps :meth:`pandas.DataFrame.iterrows`.
Expand Down Expand Up @@ -3762,16 +3760,13 @@ class NoLapDataError(Exception):
after processing the result.
"""
def __init__(self, *args):
super(NoLapDataError, self).__init__("Failed to load session because "
"the API did not provide any "
"usable data.")
super().__init__("Failed to load session because the API did not "
"provide any usable data.")


class InvalidSessionError(Exception):
"""Raised if no session for the specified event name, type and year
can be found."""

def __init__(self, *args):
super(InvalidSessionError, self).__init__(
"No matching session can be found."
)
super().__init__("No matching session can be found.")
6 changes: 2 additions & 4 deletions fastf1/ergast/interface.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import copy
import json
from typing import (
List,
Literal,
Optional,
Type,
Union
)

Expand Down Expand Up @@ -252,7 +250,7 @@ class ErgastSimpleResponse(ErgastResponseMixin, ErgastResultFrame):
_internal_names_set = set(_internal_names)

@property
def _constructor(self) -> Type["ErgastResultFrame"]:
def _constructor(self) -> type["ErgastResultFrame"]:
# drop from ErgastSimpleResponse to ErgastResultFrame, removing the
# ErgastResponseMixin because a slice of the data is no longer a full
# response and pagination, ... is therefore not supported anymore
Expand Down Expand Up @@ -363,7 +361,7 @@ def description(self) -> ErgastResultFrame:
return self._description

@property
def content(self) -> List[ErgastResultFrame]:
def content(self) -> list[ErgastResultFrame]:
"""A ``list`` of :class:`ErgastResultFrame` that contain the main
response data.
Expand Down
5 changes: 2 additions & 3 deletions fastf1/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,6 @@
from typing import (
Literal,
Optional,
Type,
Union
)

Expand Down Expand Up @@ -624,7 +623,7 @@ def _get_schedule_ff1(year):
data[f'session{j+1}_date'][i] = pd.Timestamp(date)
data[f'session{j+1}_date_Utc'][i] = pd.Timestamp(date_utc)

str().capitalize()
''.capitalize()

df = pd.DataFrame(data)
# change column names from snake_case to UpperCamelCase
Expand Down Expand Up @@ -885,7 +884,7 @@ def __init__(self, *args, year: int = 0,
self[col] = self[col].astype(_type)

@property
def _constructor_sliced_horizontal(self) -> Type["Event"]:
def _constructor_sliced_horizontal(self) -> type["Event"]:
return Event

def is_testing(self):
Expand Down
3 changes: 1 addition & 2 deletions fastf1/internals/fuzzy.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import warnings
from typing import List

import numpy as np

Expand All @@ -15,7 +14,7 @@

def fuzzy_matcher(
query: str,
reference: List[List[str]],
reference: list[list[str]],
abs_confidence: float = 0.0,
rel_confidence: float = 0.0
) -> (int, bool):
Expand Down
8 changes: 3 additions & 5 deletions fastf1/internals/pandas_extensions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import List

import numpy as np
from pandas import (
DataFrame,
Expand Down Expand Up @@ -35,7 +33,7 @@

def create_df_fast(
*,
arrays: List[np.ndarray],
arrays: list[np.ndarray],
columns: list,
fallback: bool = True
) -> DataFrame:
Expand Down Expand Up @@ -71,7 +69,7 @@ def create_df_fast(


def _fallback_create_df(
arrays: List[np.ndarray],
arrays: list[np.ndarray],
columns: list
) -> DataFrame:
data = {col: arr for col, arr in zip(columns, arrays)}
Expand All @@ -87,7 +85,7 @@ def _fallback_if_unsupported(func):

@_fallback_if_unsupported
def _unsafe_create_df_fast(
arrays: List[np.ndarray],
arrays: list[np.ndarray],
columns: list
) -> DataFrame:
# Implements parts of pandas' internal DataFrame creation mechanics
Expand Down
2 changes: 1 addition & 1 deletion fastf1/livetiming/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def save(args):


def convert(args):
with open(args.input, 'r') as infile:
with open(args.input) as infile:
messages = infile.readlines()
data, ec = messages_from_raw(messages)
with open(args.output, 'w') as outfile:
Expand Down
6 changes: 2 additions & 4 deletions fastf1/livetiming/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
import json
import logging
import time
from typing import (
Iterable,
Optional
)
from collections.abc import Iterable
from typing import Optional

import requests

Expand Down
2 changes: 1 addition & 1 deletion fastf1/livetiming/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def load(self):
next_data = None
else:
# read a new file as next file
with open(next_file, 'r') as fobj:
with open(next_file) as fobj:
next_data = fobj.readlines()

if current_data is None:
Expand Down
28 changes: 12 additions & 16 deletions fastf1/plotting/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import warnings
from typing import (
Dict,
List
)

from fastf1.plotting._constants import \
LEGACY_DRIVER_COLORS as _LEGACY_DRIVER_COLORS
Expand Down Expand Up @@ -91,11 +87,11 @@ def __getattr__(name):
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


_DEPR_COMPOUND_COLORS: Dict[str, str] = {
_DEPR_COMPOUND_COLORS: dict[str, str] = {
key: val for key, val
in _Constants['2024'].CompoundColors.items()
}
COMPOUND_COLORS: Dict[str, str]
COMPOUND_COLORS: dict[str, str]
"""
Mapping of tyre compound names to compound colors (hex color codes).
(current season only)
Expand All @@ -107,8 +103,8 @@ def __getattr__(name):
"""


_DEPR_DRIVER_COLORS: Dict[str, str] = _LEGACY_DRIVER_COLORS.copy()
DRIVER_COLORS: Dict[str, str]
_DEPR_DRIVER_COLORS: dict[str, str] = _LEGACY_DRIVER_COLORS.copy()
DRIVER_COLORS: dict[str, str]
"""
Mapping of driver names to driver colors (hex color codes).
Expand All @@ -123,8 +119,8 @@ def __getattr__(name):
"""


_DEPR_DRIVER_TRANSLATE: Dict[str, str] = _LEGACY_DRIVER_TRANSLATE.copy()
DRIVER_TRANSLATE: Dict[str, str]
_DEPR_DRIVER_TRANSLATE: dict[str, str] = _LEGACY_DRIVER_TRANSLATE.copy()
DRIVER_TRANSLATE: dict[str, str]
"""
Mapping of driver names to theirs respective abbreviations.
Expand All @@ -138,13 +134,13 @@ def __getattr__(name):
future version. Use :func:`~fastf1.plotting.get_driver_name` instead.
"""

_DEPR_TEAM_COLORS: Dict[str, str] = {
_DEPR_TEAM_COLORS: dict[str, str] = {
# str(key.value): val for key, val
# in _Constants['2024'].Colormaps[_Colormaps.Default].items()
name.replace("kick ", ""): team.TeamColor.FastF1 for name, team
in _Constants['2024'].Teams.items()
}
TEAM_COLORS: Dict[str, str]
TEAM_COLORS: dict[str, str]
"""
Mapping of team names to team colors (hex color codes).
(current season only)
Expand All @@ -154,8 +150,8 @@ def __getattr__(name):
future version. Use :func:`~fastf1.plotting.get_team_color` instead.
"""

_DEPR_TEAM_TRANSLATE: Dict[str, str] = _LEGACY_TEAM_TRANSLATE.copy()
TEAM_TRANSLATE: Dict[str, str]
_DEPR_TEAM_TRANSLATE: dict[str, str] = _LEGACY_TEAM_TRANSLATE.copy()
TEAM_TRANSLATE: dict[str, str]
"""
Mapping of team names to theirs respective abbreviations.
Expand All @@ -164,8 +160,8 @@ def __getattr__(name):
future version. Use :func:`~fastf1.plotting.get_team_name` instead.
"""

_DEPR_COLOR_PALETTE: List[str] = _COLOR_PALETTE.copy()
COLOR_PALETTE: List[str]
_DEPR_COLOR_PALETTE: list[str] = _COLOR_PALETTE.copy()
COLOR_PALETTE: list[str]
"""
The default color palette for matplotlib plot lines in fastf1's color scheme.
Expand Down
8 changes: 2 additions & 6 deletions fastf1/plotting/_backend.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import dataclasses
from typing import (
Dict,
List
)

import fastf1._api
from fastf1.plotting._base import (
Expand All @@ -16,12 +12,12 @@

def _load_drivers_from_f1_livetiming(
*, api_path: str, year: str
) -> List[_Team]:
) -> list[_Team]:
# load the driver information for the determined session
driver_info = fastf1._api.driver_info(api_path)

# parse the data into the required format
teams: Dict[str, _Team] = dict()
teams: dict[str, _Team] = dict()

# Sorting by driver number here will directly guarantee that drivers
# are sorted by driver number within each team. This has two advantages:
Expand Down
Loading

0 comments on commit f768b9f

Please sign in to comment.