Skip to content

Commit

Permalink
Apply ruff rules UP006 and UP007 (PlasmaPy#2504)
Browse files Browse the repository at this point in the history
* Apply changes from UP007

* Manually change annotations to | syntax

* Revert to typing.Union syntax

* Add changelog entry

* Annotate ParticleLike & ParticleListLike with TypeAlias

* Minor correction in mypy.ini

* Add type hint

* Follow recommended type hint practices

* Add type: ignore comments

* Update type hint annotation
  • Loading branch information
namurphy authored Feb 7, 2024
1 parent c6f2ab2 commit c8b95fa
Show file tree
Hide file tree
Showing 53 changed files with 319 additions and 364 deletions.
3 changes: 1 addition & 2 deletions .github/scripts/authors_in_cff.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import os
import pathlib
import sys
from typing import Optional

import requests

Expand All @@ -27,7 +26,7 @@ def get_pr_authors() -> set[str]:
return authors - set(EXCLUDED_USERS)


def check_citation_file(authors: set[str]) -> tuple[bool, Optional[str]]:
def check_citation_file(authors: set[str]) -> tuple[bool, str | None]:
"""Verify that all authors of a PR are included in :file:`CITATION.cff`."""
with pathlib.Path("CITATION.cff").open() as file:
contents = file.read()
Expand Down
3 changes: 3 additions & 0 deletions changelog/2504.trivial.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Changed type hint annotations to be consistent with :pep:`604`. Type
unions are now made using the ``|`` operator rather than with
`typing.Union`.
3 changes: 1 addition & 2 deletions docs/_cff_to_rst.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
reStructuredText-formatted list.
"""
import pathlib
from typing import Union

import yaml
from unidecode import unidecode
Expand All @@ -16,7 +15,7 @@
obsolete_github_usernames = {}


def parse_cff(filename: str) -> dict[str, Union[str, list[dict[str, str]]]]:
def parse_cff(filename: str) -> dict[str, str | list[dict[str, str]]]:
"""
Parse a :file:`CITATION.cff` file into a dictionary.
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[mypy]
python_version = '3.10'
python_version = 3.10
mypy_path = ./type_stubs
exclude = (?x)(
docs|
Expand Down
17 changes: 8 additions & 9 deletions plasmapy/analysis/fit_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import warnings
from abc import ABC, abstractmethod
from collections import namedtuple
from typing import Optional

import numpy as np
from scipy.optimize import curve_fit, fsolve
Expand All @@ -36,8 +35,8 @@ class AbstractFitFunction(ABC):

def __init__(
self,
params: Optional[tuple[float, ...]] = None,
param_errors: Optional[tuple[float, ...]] = None,
params: tuple[float, ...] | None = None,
param_errors: tuple[float, ...] | None = None,
) -> None:
"""
Parameters
Expand Down Expand Up @@ -225,7 +224,7 @@ def FitParamTuple(self):
return self._FitParamTuple

@property
def params(self) -> Optional[tuple]:
def params(self) -> tuple | None:
"""The fitted parameters for the fit function."""
if self._params is None:
return self._params
Expand All @@ -247,7 +246,7 @@ def params(self, val) -> None:
)

@property
def param_errors(self) -> Optional[tuple]:
def param_errors(self) -> tuple | None:
"""The associated errors of the fitted :attr:`params`."""
if self._param_errors is None:
return self._param_errors
Expand Down Expand Up @@ -801,8 +800,8 @@ class ExponentialPlusLinear(AbstractFitFunction):

def __init__(
self,
params: Optional[tuple[float, ...]] = None,
param_errors: Optional[tuple[float, ...]] = None,
params: tuple[float, ...] | None = None,
param_errors: tuple[float, ...] | None = None,
) -> None:
self._exponential = Exponential()
self._linear = Linear()
Expand Down Expand Up @@ -939,8 +938,8 @@ class ExponentialPlusOffset(AbstractFitFunction):

def __init__(
self,
params: Optional[tuple[float, ...]] = None,
param_errors: Optional[tuple[float, ...]] = None,
params: tuple[float, ...] | None = None,
param_errors: tuple[float, ...] | None = None,
) -> None:
self._explin = ExponentialPlusLinear()
super().__init__(params=params, param_errors=param_errors)
Expand Down
14 changes: 7 additions & 7 deletions plasmapy/analysis/swept_langmuir/floating_potential.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import numbers
import warnings
from typing import NamedTuple, Optional, Union
from typing import NamedTuple

import numpy as np

Expand All @@ -21,32 +21,32 @@ class VFExtras(NamedTuple):
`~plasmapy.analysis.swept_langmuir.floating_potential.find_floating_potential`.
"""

vf_err: Optional[float]
vf_err: float | None
"""
Alias for field number 0, the error in the calculated floating
potential from the floating potential curve fit.
"""

rsq: Optional[float]
rsq: float | None
"""
Alias for field number 1, the r-squared value of the ion-saturation
curve fit.
"""

fitted_func: Optional[float]
fitted_func: float | None
"""
Alias for field number 2, the :term:`fit-function` fitted during
the floating potential curve fit.
"""

islands: Optional[list[slice]]
islands: list[slice] | None
"""
Alias for field number 3, a list of `slice` objects representing
the indices of the identified crossing-islands discovered during
the floating potential curve fit.
"""

fitted_indices: Optional[slice]
fitted_indices: slice | None
"""
Alias for field number 4, the indices used in the floating potential
curve fit.
Expand All @@ -57,7 +57,7 @@ def find_floating_potential( # noqa: C901, PLR0912, PLR0915
voltage: np.ndarray,
current: np.ndarray,
threshold: int = 1,
min_points: Optional[Union[int, float]] = None,
min_points: float | None = None,
fit_type: str = "exponential",
) -> tuple[np.floating, VFExtras]:
"""
Expand Down
12 changes: 6 additions & 6 deletions plasmapy/analysis/swept_langmuir/ion_saturation_current.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
__aliases__ = ["find_isat_"]

import numbers
from typing import Any, NamedTuple, Optional
from typing import Any, NamedTuple

import numpy as np

Expand All @@ -21,19 +21,19 @@ class ISatExtras(NamedTuple):
`~plasmapy.analysis.swept_langmuir.ion_saturation_current.find_ion_saturation_current`.
"""

rsq: Optional[float]
rsq: float | None
"""
Alias for field number 0, the r-squared value of the ion-saturation
curve fit.
"""

fitted_func: Optional[ffuncs.AbstractFitFunction]
fitted_func: ffuncs.AbstractFitFunction | None
"""
Alias for field number 1, the :term:`fit-function` fitted during
the ion-saturation curve fit.
"""

fitted_indices: Optional[slice]
fitted_indices: slice | None
"""
Alias for field number 2, the indices used in the ion-saturation
curve fit.
Expand All @@ -45,8 +45,8 @@ def find_ion_saturation_current(
current: np.ndarray,
*,
fit_type: str = "exp_plus_linear",
current_bound: Optional[numbers.Real] = None,
voltage_bound: Optional[numbers.Real] = None,
current_bound: numbers.Real | None = None,
voltage_bound: numbers.Real | None = None,
) -> tuple[ffuncs.Linear, ISatExtras]:
"""
Determines the ion-saturation current (:math:`I_{sat}`) for a given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"Layer",
]

from typing import Optional

import astropy.units as u
import numpy as np
Expand Down Expand Up @@ -62,7 +61,7 @@ def __init__(
thickness: u.Quantity[u.m],
energy_axis: u.Quantity[u.J],
stopping_power: u.Quantity[u.J / u.m, u.J * u.m**2 / u.kg],
mass_density: Optional[u.Quantity[u.kg / u.m**3]] = None,
mass_density: u.Quantity[u.kg / u.m**3] | None = None,
active: bool = True,
name: str = "",
) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import sys
import warnings
from collections.abc import Iterable
from typing import Union

import astropy.constants as const
import astropy.units as u
Expand Down Expand Up @@ -125,7 +124,7 @@ class Tracker:

def __init__(
self,
grids: Union[AbstractGrid, Iterable[AbstractGrid]],
grids: AbstractGrid | Iterable[AbstractGrid],
source: u.Quantity[u.m],
detector: u.Quantity[u.m],
detector_hdir=None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
Tests for proton radiography functions
"""

from typing import Optional

import astropy.units as u
import numpy as np
Expand All @@ -22,8 +21,8 @@ def _test_grid( # noqa: C901, PLR0912
B0: u.Quantity[u.T] = 10 * u.T,
E0: u.Quantity[u.V / u.m] = 5e8 * u.V / u.m,
phi0: u.Quantity[u.V] = 1.4e5 * u.V,
a: Optional[u.Quantity[u.m]] = None,
b: Optional[u.Quantity[u.m]] = None,
a: u.Quantity[u.m] | None = None,
b: u.Quantity[u.m] | None = None,
):
r"""
Generates grids representing some common physical scenarios for testing
Expand Down
12 changes: 6 additions & 6 deletions plasmapy/diagnostics/thomson.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import numbers
import warnings
from collections.abc import Callable
from typing import Any, Optional, Union
from typing import Any

import astropy.constants as const
import astropy.units as u
Expand Down Expand Up @@ -63,9 +63,9 @@ def spectral_density_lite(
ion_vel: np.ndarray,
probe_vec: np.ndarray,
scatter_vec: np.ndarray,
instr_func_arr: Optional[np.ndarray] = None,
notch: Optional[np.ndarray] = None,
) -> tuple[Union[np.floating, np.ndarray], np.ndarray]:
instr_func_arr: np.ndarray | None = None,
notch: np.ndarray | None = None,
) -> tuple[np.floating | np.ndarray, np.ndarray]:
r"""
The :term:`lite-function` version of
`~plasmapy.diagnostics.thomson.spectral_density`. Performs the same
Expand Down Expand Up @@ -297,9 +297,9 @@ def spectral_density( # noqa: C901, PLR0912, PLR0915
ion_vel: u.Quantity[u.m / u.s] = None,
probe_vec=None,
scatter_vec=None,
instr_func: Optional[Callable] = None,
instr_func: Callable | None = None,
notch: u.m = None,
) -> tuple[Union[np.floating, np.ndarray], np.ndarray]:
) -> tuple[np.floating | np.ndarray, np.ndarray]:
r"""Calculate the spectral density function for Thomson scattering of
a probe laser beam by a multi-species Maxwellian plasma.
Expand Down
5 changes: 2 additions & 3 deletions plasmapy/dispersion/analytical/mhd_waves_.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from abc import ABC, abstractmethod
from collections import namedtuple
from numbers import Integral, Real
from typing import Optional

import astropy.units as u
import numpy as np
Expand Down Expand Up @@ -44,8 +43,8 @@ def __init__(
*,
T: u.Quantity[u.K] = 0 * u.K,
gamma: float = 5 / 3,
mass_numb: Optional[Integral] = None,
Z: Optional[Real] = None,
mass_numb: Integral | None = None,
Z: Real | None = None,
) -> None:
# validate arguments
for arg_name in ("B", "density", "T"):
Expand Down
5 changes: 2 additions & 3 deletions plasmapy/dispersion/analytical/two_fluid_.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import warnings
from numbers import Integral, Real
from typing import Optional

import astropy.units as u
import numpy as np
Expand Down Expand Up @@ -37,8 +36,8 @@ def two_fluid(
T_i: u.Quantity[u.K],
gamma_e: Real = 1,
gamma_i: Real = 3,
mass_numb: Optional[Integral] = None,
Z: Optional[Real] = None,
mass_numb: Integral | None = None,
Z: Real | None = None,
):
r"""
Using the solution provided by :cite:t:`bellan:2012`, calculate the
Expand Down
9 changes: 4 additions & 5 deletions plasmapy/dispersion/dispersion_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@


from numbers import Complex
from typing import Union

import astropy.units as u
import numpy as np
from scipy.special import wofz as faddeeva_function


def plasma_dispersion_func(
zeta: Union[Complex, np.ndarray, u.Quantity[u.dimensionless_unscaled]],
) -> Union[Complex, np.ndarray, u.Quantity[u.dimensionless_unscaled]]:
zeta: Complex | np.ndarray | u.Quantity[u.dimensionless_unscaled],
) -> Complex | np.ndarray | u.Quantity[u.dimensionless_unscaled]:
r"""
Calculate the plasma dispersion function.
Expand Down Expand Up @@ -80,8 +79,8 @@ def plasma_dispersion_func(


def plasma_dispersion_func_deriv(
zeta: Union[Complex, np.ndarray, u.Quantity[u.dimensionless_unscaled]],
) -> Union[Complex, np.ndarray, u.Quantity[u.dimensionless_unscaled]]:
zeta: Complex | np.ndarray | u.Quantity[u.dimensionless_unscaled],
) -> Complex | np.ndarray | u.Quantity[u.dimensionless_unscaled]:
r"""
Calculate the derivative of the plasma dispersion function.
Expand Down
9 changes: 4 additions & 5 deletions plasmapy/dispersion/dispersionfunction.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
__all__ = ["plasma_dispersion_func", "plasma_dispersion_func_deriv"]

import warnings
from typing import Union

import astropy.units as u
import numpy as np
Expand Down Expand Up @@ -49,8 +48,8 @@ def plasma_dispersion_func_lite(zeta):

@bind_lite_func(plasma_dispersion_func_lite)
def plasma_dispersion_func(
zeta: Union[complex, np.ndarray, u.Quantity],
) -> Union[complex, np.ndarray, u.Quantity]:
zeta: complex | np.ndarray | u.Quantity,
) -> complex | np.ndarray | u.Quantity:
r"""
Calculate the plasma dispersion function.
Expand Down Expand Up @@ -100,8 +99,8 @@ def plasma_dispersion_func_deriv_lite(zeta):

@bind_lite_func(plasma_dispersion_func_deriv_lite)
def plasma_dispersion_func_deriv(
zeta: Union[complex, np.ndarray, u.Quantity],
) -> Union[complex, np.ndarray, u.Quantity]:
zeta: complex | np.ndarray | u.Quantity,
) -> complex | np.ndarray | u.Quantity:
r"""
Calculate the derivative of the plasma dispersion function.
Expand Down
Loading

0 comments on commit c8b95fa

Please sign in to comment.