Skip to content

Commit

Permalink
chore: use Self (#398)
Browse files Browse the repository at this point in the history
* chore: use Self

Signed-off-by: Henry Schreiner <[email protected]>

* ci: recache

Signed-off-by: Henry Schreiner <[email protected]>

* Cleanup

* Reverse to previous version of mypy

---------

Signed-off-by: Henry Schreiner <[email protected]>
Co-authored-by: Eduardo Rodrigues <[email protected]>
  • Loading branch information
henryiii and eduardo-rodrigues authored Nov 27, 2023
1 parent 52a51ca commit c9b6f7b
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 33 deletions.
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ci:

repos:
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.10.1
rev: 23.11.0
hooks:
- id: black-jupyter

Expand All @@ -24,7 +24,7 @@ repos:
- id: end-of-file-fixer

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.1.4"
rev: "v0.1.5"
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]
Expand All @@ -34,7 +34,7 @@ repos:
hooks:
- id: mypy
files: '^src/decaylanguage/(decay|dec|utils)/'
additional_dependencies: [attrs, particle, importlib_resources, numpy]
additional_dependencies: [attrs, particle, importlib_resources, numpy>=1.26]

- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
Expand Down
Empty file.
20 changes: 20 additions & 0 deletions src/decaylanguage/_compat/typing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from __future__ import annotations

import sys
import typing

if sys.version_info < (3, 8):
from typing_extensions import TypedDict
else:
from typing import TypedDict

if sys.version_info < (3, 11):
if typing.TYPE_CHECKING:
from typing_extensions import Self
else:
Self = object
else:
from typing import Self


__all__ = ["TypedDict", "Self"]
10 changes: 3 additions & 7 deletions src/decaylanguage/dec/dec.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,14 @@
from io import StringIO
from itertools import zip_longest
from pathlib import Path
from typing import Any, TypeVar
from typing import Any

from lark import Lark, Token, Transformer, Tree, Visitor
from particle import Particle
from particle.converters import PDG2EvtGenNameMap

from .. import data
from .._compat.typing import Self
from ..decay.decay import _expand_decay_modes
from ..utils import charge_conjugate_name
from .enums import PhotosEnum
Expand All @@ -67,9 +68,6 @@ class DecayNotFound(RuntimeError):
pass


Self_DecFileParser = TypeVar("Self_DecFileParser", bound="DecFileParser")


class DecFileParser:
"""
The class to parse a .dec decay file.
Expand Down Expand Up @@ -142,9 +140,7 @@ def __init__(self, *filenames: str | os.PathLike[str]) -> None:
self._include_ccdecays = True

@classmethod
def from_string(
cls: type[Self_DecFileParser], filecontent: str
) -> Self_DecFileParser:
def from_string(cls, filecontent: str) -> Self:
"""
Constructor from a .dec decay file provided as a multi-line string.
Expand Down
35 changes: 12 additions & 23 deletions src/decaylanguage/decay/decay.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,15 @@
from collections import Counter
from copy import deepcopy
from itertools import product
from typing import TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, TypeVar, Union
from typing import TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Union

from particle import PDGID, ParticleNotFound
from particle.converters import EvtGenName2PDGIDBiMap
from particle.exceptions import MatchingIDNotFound

from .._compat.typing import Self
from ..utils import DescriptorFormat, charge_conjugate_name

Self_DaughtersDict = TypeVar("Self_DaughtersDict", bound="DaughtersDict")

if TYPE_CHECKING:
CounterStr = Counter[str] # pragma: no cover
else:
Expand Down Expand Up @@ -107,9 +106,7 @@ def to_list(self) -> list[str]:
"""
return sorted(self.elements())

def charge_conjugate(
self: Self_DaughtersDict, pdg_name: bool = False
) -> Self_DaughtersDict:
def charge_conjugate(self, pdg_name: bool = False) -> Self:
"""
Return the charge-conjugate final state.
Expand Down Expand Up @@ -156,7 +153,7 @@ def __len__(self) -> int:
"""
return sum(self.values())

def __add__(self: Self_DaughtersDict, other: Self_DaughtersDict) -> Self_DaughtersDict: # type: ignore[override]
def __add__(self, other: Self) -> Self: # type: ignore[override]
"""
Add two final states, particle-type-wise.
"""
Expand All @@ -167,9 +164,6 @@ def __iter__(self) -> Iterator[str]:
return self.elements()


Self_DecayMode = TypeVar("Self_DecayMode", bound="DecayMode")


class DecayMode:
"""
Class holding a particle decay mode, which is typically a branching fraction
Expand Down Expand Up @@ -254,9 +248,9 @@ def __init__(

@classmethod
def from_dict(
cls: type[Self_DecayMode],
cls,
decay_mode_dict: dict[str, int | float | str | list[str]],
) -> Self_DecayMode:
) -> Self:
"""
Constructor from a dictionary of the form
{'bf': <float>, 'fs': [...], ...}.
Expand Down Expand Up @@ -301,11 +295,11 @@ def from_dict(

@classmethod
def from_pdgids(
cls: type[Self_DecayMode],
cls,
bf: float = 0,
daughters: list[int] | tuple[int] | None = None,
**info: Any,
) -> Self_DecayMode:
) -> Self:
"""
Constructor for a final state given as a list of particle PDG IDs.
Expand Down Expand Up @@ -397,9 +391,7 @@ def to_dict(self) -> dict[str, int | float | str | list[str]]:
d["model_params"] = ""
return d # type: ignore[return-value]

def charge_conjugate(
self: Self_DecayMode, pdg_name: bool = False
) -> Self_DecayMode:
def charge_conjugate(self, pdg_name: bool = False) -> Self:
"""
Return the charge-conjugate decay mode.
Expand Down Expand Up @@ -444,7 +436,6 @@ def __str__(self) -> str:
return repr(self)


Self_DecayChain = TypeVar("Self_DecayChain", bound="DecayChain")
DecayModeDict = Dict[str, Union[float, str, List[Any]]]
DecayChainDict = Dict[str, List[DecayModeDict]]

Expand Down Expand Up @@ -772,9 +763,7 @@ def __init__(self, mother: str, decays: dict[str, DecayMode]) -> None:
self.decays = decays

@classmethod
def from_dict(
cls: type[Self_DecayChain], decay_chain_dict: DecayChainDict
) -> Self_DecayChain:
def from_dict(cls, decay_chain_dict: DecayChainDict) -> Self:
"""
Constructor from a decay chain represented as a dictionary.
The format is the same as that returned by
Expand Down Expand Up @@ -966,9 +955,9 @@ def recursively_replace(mother: str) -> DecayDict:
return recursively_replace(self.mother)

def flatten(
self: Self_DecayChain,
self,
stable_particles: Iterable[dict[str, int] | list[str] | str] = (),
) -> Self_DecayChain:
) -> Self:
"""
Flatten the decay chain replacing all intermediate, decaying particles,
with their final states.
Expand Down

0 comments on commit c9b6f7b

Please sign in to comment.