Skip to content

Commit

Permalink
chore: linting + upgrade syntax to Python 3.8+ (PySport#382)
Browse files Browse the repository at this point in the history
  • Loading branch information
probberechts authored Dec 26, 2024
1 parent 9cee426 commit e059e3c
Show file tree
Hide file tree
Showing 73 changed files with 210 additions and 175 deletions.
1 change: 0 additions & 1 deletion kloppy/_providers/secondspectrum.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import Optional
import contextlib

from kloppy.domain import TrackingDataset
from kloppy.infra.serializers.tracking.secondspectrum import (
Expand Down
7 changes: 1 addition & 6 deletions kloppy/config.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import os
from contextlib import contextmanager
from copy import copy
from typing import Any, Optional, Union
from typing import Any, Optional, TypedDict, Union

from kloppy.domain import EventFactory

try:
from typing import TypedDict
except ImportError:
from mypy_extensions import TypedDict

try:
from typing import Literal
except ImportError:
Expand Down
2 changes: 2 additions & 0 deletions kloppy/datafactory.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from ._providers.datafactory import load

__all__ = ["load"]
6 changes: 1 addition & 5 deletions kloppy/domain/models/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Generic,
Iterable,
List,
Literal,
NewType,
Optional,
TypeVar,
Expand All @@ -21,11 +22,6 @@
from ...utils import deprecated, snake_case
from .position import PositionType

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

if sys.version_info >= (3, 11):
from typing import Self
else:
Expand Down
1 change: 0 additions & 1 deletion kloppy/domain/models/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
Generic,
List,
Literal,
NamedTuple,
Optional,
Tuple,
TypeVar,
Expand Down
11 changes: 10 additions & 1 deletion kloppy/domain/services/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from kloppy.domain import AttackingDirection, Frame, Ground

from .transformers import DatasetTransformer, DatasetTransformerBuilder
from .event_factory import EventFactory, create_event
from .transformers import DatasetTransformer, DatasetTransformerBuilder

# NOT YET: from .enrichers import TrackingPossessionEnricher

Expand Down Expand Up @@ -35,3 +35,12 @@ def attacking_direction_from_frame(frame: Frame) -> AttackingDirection:
return AttackingDirection.LTR
else:
return AttackingDirection.RTL


__all__ = [
"DatasetTransformer",
"DatasetTransformerBuilder",
"EventFactory",
"create_event",
"attacking_direction_from_frame",
]
19 changes: 14 additions & 5 deletions kloppy/domain/services/matchers/pattern/event.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
from collections import defaultdict
from dataclasses import dataclass
from functools import partial
from typing import Callable, Tuple, Dict, List, Iterator
from typing import Callable, Dict, Iterator, List, Tuple

from kloppy.domain import (
CarryEvent,
Event,
EventDataset,
PassEvent,
ShotEvent,
CarryEvent,
TakeOnEvent,
Event,
)
from .regexp import *
from .regexp import _make_match, _TrailItem

from .regexp import (
Final,
Matcher,
Node,
Out,
RegExp,
Tok,
_make_match,
_TrailItem,
)
from .regexp.regexp import _Match


Expand Down
8 changes: 4 additions & 4 deletions kloppy/domain/services/matchers/pattern/regexp/ast.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field, replace
from functools import reduce
from typing import Generic, Text, Union
from typing import Generic, Union

from .matchers import Matcher, Out, Tok

Expand Down Expand Up @@ -37,12 +37,12 @@ def __or__(self, other: "Node"):

return Alternation(self, other)

def __getitem__(self, item: Text):
def __getitem__(self, item: str):
"""
Generates a capture group
"""

if not isinstance(item, Text):
if not isinstance(item, str):
raise KeyError("Cannot capture with a key other than a string")

return Capture(name=item, statement=self)
Expand Down Expand Up @@ -192,7 +192,7 @@ class Capture(DumbHash, Node):
Represents a capture group around the statement
"""

name: Text
name: str
statement: Node = field(repr=False)

def copy(self):
Expand Down
7 changes: 3 additions & 4 deletions kloppy/domain/services/matchers/pattern/regexp/matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
Iterator,
Mapping,
Sequence,
Text,
Tuple,
TypeVar,
Union,
Expand Down Expand Up @@ -36,7 +35,7 @@ class _TrailItem(Generic[Out]):
"""

item: Out
data: Dict[Text, Sequence[Text]]
data: Dict[str, Sequence[str]]

@property
def _comparable(self):
Expand Down Expand Up @@ -108,7 +107,7 @@ def match(


class AttributeHasValue(Matcher):
def __init__(self, attribute: Text, value: Any):
def __init__(self, attribute: str, value: Any):
self.attribute = attribute
self.value = value

Expand Down Expand Up @@ -146,7 +145,7 @@ def __repr__(self):

class Anything(Matcher):
def __repr__(self):
return f"Anything()"
return "Anything()"

def match(
self, token: Tok, trail: Tuple[_TrailItem[Out], ...]
Expand Down
7 changes: 3 additions & 4 deletions kloppy/domain/services/matchers/pattern/regexp/regexp.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
List,
Mapping,
Sequence,
Text,
Tuple,
)

Expand Down Expand Up @@ -355,7 +354,7 @@ class _Match(Generic[Out]):

def __init__(self, start_pos: int):
self.start_pos = start_pos
self.children: Dict[Text, List[_Match]] = {}
self.children: Dict[str, List[_Match]] = {}
self.trail: List[Out] = []
self._stack: List[Capture] = []

Expand Down Expand Up @@ -472,7 +471,7 @@ class Match(Generic[Out]):

# Sub-groups that matched. As several groups could be matching, a list
# is returned so you can access each one of them.
children: Mapping[Text, List["Match"]]
children: Mapping[str, List["Match"]]

# Trail of matched items. It's the output of the matcher, not the input
# tokens.
Expand Down Expand Up @@ -637,7 +636,7 @@ def match(
)

def _de_duplicate(
self, stack: Iterator[Explorer[Tok, Out]], key: Text = "signature"
self, stack: Iterator[Explorer[Tok, Out]], key: str = "signature"
) -> Iterator[Explorer[Tok, Out]]:
"""
As there is potentially several paths that lead to the same result, we
Expand Down
6 changes: 3 additions & 3 deletions kloppy/domain/services/state_builder/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from dataclasses import replace
from typing import List

from kloppy.domain import List, EventDataset
from kloppy.domain import EventDataset

# register all of them
from . import builders as _builders

from . import builders as _builders # noqa: F401
from .registered import create_state_builder


Expand Down
9 changes: 8 additions & 1 deletion kloppy/domain/services/state_builder/builders/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
from .formation import FormationStateBuilder
from .lineup import LineupStateBuilder
from .score import ScoreStateBuilder
from .sequence import SequenceStateBuilder
from .formation import FormationStateBuilder

__all__ = [
"LineupStateBuilder",
"ScoreStateBuilder",
"SequenceStateBuilder",
"FormationStateBuilder",
]
9 changes: 4 additions & 5 deletions kloppy/domain/services/state_builder/builders/lineup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
PlayerOnEvent,
CardEvent,
CardType,
Provider,
)
from ..builder import StateBuilder

Expand All @@ -24,16 +23,16 @@ class LineupStateBuilder(StateBuilder):
def initial_state(self, dataset: EventDataset) -> Lineup:
return Lineup(
players=(
set(
{
player
for player in dataset.metadata.teams[0].players
if player.starting
)
| set(
}
| {
player
for player in dataset.metadata.teams[1].players
if player.starting
)
}
)
)

Expand Down
4 changes: 1 addition & 3 deletions kloppy/domain/services/state_builder/registered.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ class RegisteredStateBuilder(abc.ABCMeta):
def __new__(mcs, cls_name, bases, class_dict):
name = camelcase_to_snakecase(cls_name)
class_dict["name"] = name
builder_cls = super(RegisteredStateBuilder, mcs).__new__(
mcs, cls_name, bases, class_dict
)
builder_cls = super().__new__(mcs, cls_name, bases, class_dict)
if not inspect.isabstract(builder_cls):
_STATE_BUILDER_REGISTRY[
name.replace("_state_builder", "")
Expand Down
2 changes: 2 additions & 0 deletions kloppy/domain/services/transformers/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from .dataset import DatasetTransformer, DatasetTransformerBuilder

__all__ = ["DatasetTransformer", "DatasetTransformerBuilder"]
6 changes: 3 additions & 3 deletions kloppy/domain/services/transformers/attribute.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def __init__(
):
if include and exclude:
raise KloppyParameterError(
f"Cannot specify both include as exclude"
"Cannot specify both include as exclude"
)

self.exclude = exclude or []
Expand Down Expand Up @@ -250,7 +250,7 @@ def __init__(
):
if include and exclude:
raise KloppyParameterError(
f"Cannot specify both include as exclude"
"Cannot specify both include as exclude"
)

self.exclude = exclude or []
Expand Down Expand Up @@ -322,7 +322,7 @@ def __init__(
):
if include and exclude:
raise KloppyParameterError(
f"Cannot specify both include as exclude"
"Cannot specify both include as exclude"
)

self.exclude = exclude or []
Expand Down
2 changes: 1 addition & 1 deletion kloppy/domain/services/transformers/data_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def converter(data_record: T) -> Dict[str, Any]:
res = column(data_record)
if not isinstance(res, dict):
raise KloppyError(
f"A function column should return a dictionary"
"A function column should return a dictionary"
)
row.update(res)
else:
Expand Down
3 changes: 2 additions & 1 deletion kloppy/infra/io/adapters/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

from kloppy.config import get_config
from kloppy.exceptions import AdapterError, InputNotFoundError

from .adapter import Adapter

try:
from js import XMLHttpRequest
from js import XMLHttpRequest # noqa: F401

RUNS_IN_BROWSER = True
except ImportError:
Expand Down
3 changes: 1 addition & 2 deletions kloppy/infra/serializers/code/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from abc import ABC, abstractmethod
from typing import Tuple, Dict, Generic, TypeVar
from typing import Generic, TypeVar

from kloppy.utils import Readable
from kloppy.domain import CodeDataset


Expand Down
5 changes: 5 additions & 0 deletions kloppy/infra/serializers/event/datafactory/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
from .deserializer import DatafactoryDeserializer, DatafactoryInputs

__all__ = [
"DatafactoryDeserializer",
"DatafactoryInputs",
]
13 changes: 2 additions & 11 deletions kloppy/infra/serializers/event/datafactory/deserializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,34 @@
import logging
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from typing import IO, Dict, List, NamedTuple, Tuple, Union
from typing import IO, Dict, List, NamedTuple, Tuple

from kloppy.domain import (
AttackingDirection,
BallOutEvent,
BallState,
BodyPart,
BodyPartQualifier,
CardEvent,
CardType,
DatasetFlag,
Event,
EventDataset,
FoulCommittedEvent,
GenericEvent,
Ground,
Metadata,
Orientation,
PassEvent,
PassResult,
Period,
Player,
Point,
Provider,
Qualifier,
RecoveryEvent,
Score,
SetPieceQualifier,
SetPieceType,
ShotEvent,
ShotResult,
SubstitutionEvent,
Team,
)
from kloppy.exceptions import DeserializationError
from kloppy.infra.serializers.event.deserializer import EventDataDeserializer
from kloppy.utils import Readable, performance_logging
from kloppy.utils import performance_logging

logger = logging.getLogger(__name__)

Expand Down
Loading

0 comments on commit e059e3c

Please sign in to comment.