Skip to content

Commit bd5aa91

Browse files
Convert typing to PEP604 (#5531)
Our minimal supported Python version is now `3.11`, so we can adopt [`PEP604` type syntax](https://peps.python.org/pep-0604/): - `typing.Optional[X]` -> `X | None` - `typing.Union[A, B]` -> `A | B`
1 parent 22433b4 commit bd5aa91

45 files changed

Lines changed: 355 additions & 336 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎package/CHANGELOG‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ Enhancements
2929
(Issue #5362, PR #5482)
3030

3131
Changes
32+
* Type hints now use PEP 604 syntax (``X | None``, ``A | B``) instead of
33+
``typing.Optional``/``typing.Union``; parameters that default to ``None``
34+
are annotated as optional and their docstrings updated to match.
35+
`lib.distances.apply_PBC` no longer defaults ``box`` to ``None`` (it was
36+
always required) and ``return_distances`` in the capped distance functions
37+
is annotated as ``bool`` (PR #5531)
3238

3339
Deprecations
3440

‎package/MDAnalysis/__init__.py‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,6 @@
154154

155155
import logging
156156
import warnings
157-
from typing import Dict
158157

159158

160159
logger = logging.getLogger("MDAnalysis.__init__")
@@ -169,21 +168,21 @@
169168

170169
# Registry of Readers, Parsers and Writers known to MDAnalysis
171170
# Metaclass magic fills these as classes are declared.
172-
_READERS: Dict = {}
173-
_READER_HINTS: Dict = {}
174-
_SINGLEFRAME_WRITERS: Dict = {}
175-
_MULTIFRAME_WRITERS: Dict = {}
176-
_PARSERS: Dict = {}
177-
_PARSER_HINTS: Dict = {}
178-
_SELECTION_WRITERS: Dict = {}
179-
_CONVERTERS: Dict = {}
171+
_READERS: dict = {}
172+
_READER_HINTS: dict = {}
173+
_SINGLEFRAME_WRITERS: dict = {}
174+
_MULTIFRAME_WRITERS: dict = {}
175+
_PARSERS: dict = {}
176+
_PARSER_HINTS: dict = {}
177+
_SELECTION_WRITERS: dict = {}
178+
_CONVERTERS: dict = {}
180179
# Registry of TopologyAttributes
181-
_TOPOLOGY_ATTRS: Dict = {} # {attrname: cls}
182-
_TOPOLOGY_TRANSPLANTS: Dict = (
180+
_TOPOLOGY_ATTRS: dict = {} # {attrname: cls}
181+
_TOPOLOGY_TRANSPLANTS: dict = (
183182
{}
184183
) # {name: [attrname, method, transplant class]}
185-
_TOPOLOGY_ATTRNAMES: Dict = {} # {lower case name w/o _ : name}
186-
_GUESSERS: Dict = {}
184+
_TOPOLOGY_ATTRNAMES: dict = {} # {lower case name w/o _ : name}
185+
_GUESSERS: dict = {}
187186

188187
# custom exceptions and warnings
189188
from .exceptions import (

‎package/MDAnalysis/analysis/align.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1019,12 +1019,12 @@ def __init__(
10191019
Will be removed in MDAnalysis 3.0.0. Please use
10201020
:attr:`results.universe` instead.
10211021
1022-
results.positions : np.ndarray(dtype=float)
1022+
results.positions : numpy.ndarray(dtype=float)
10231023
Average positions
10241024
10251025
.. versionadded:: 2.0.0
10261026
1027-
positions : np.ndarray(dtype=float)
1027+
positions : numpy.ndarray(dtype=float)
10281028
Alias to the :attr:`results.positions` attribute.
10291029
10301030
.. deprecated:: 2.0.0

‎package/MDAnalysis/analysis/backends.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,12 @@
3737
"""
3838

3939
import warnings
40-
from typing import Callable
40+
from collections.abc import Callable
41+
from typing import Literal
4142
from MDAnalysis.lib.util import is_installed
4243

44+
DefaultBackendOptions = Literal["serial", "multiprocessing", "dask"]
45+
4346

4447
class BackendBase:
4548
"""Base class for backend implementation.

‎package/MDAnalysis/analysis/base.py‎

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def _get_aggregator(self):
152152
import logging
153153
import warnings
154154
from functools import partial
155-
from typing import Iterable, Union
155+
from collections.abc import Iterable
156156

157157
import numpy as np
158158
from .. import coordinates
@@ -164,6 +164,7 @@ def _get_aggregator(self):
164164
BackendMultiprocessing,
165165
BackendSerial,
166166
BackendBase,
167+
DefaultBackendOptions,
167168
)
168169
from .results import Results, ResultsGroup
169170

@@ -352,7 +353,7 @@ def __init__(self, trajectory, verbose=False, **kwargs):
352353

353354
def _define_run_frames(
354355
self, trajectory, start=None, stop=None, step=None, frames=None
355-
) -> Union[slice, np.ndarray]:
356+
) -> slice | np.ndarray:
356357
"""Defines limits for the whole run, as passed by self.run() arguments
357358
358359
Parameters
@@ -371,7 +372,7 @@ def _define_run_frames(
371372
372373
Returns
373374
-------
374-
Union[slice, np.ndarray]
375+
slice or numpy.ndarray
375376
Appropriate slicer for the trajectory that would give correct iteraction
376377
order via trajectory[slicer]
377378
@@ -399,14 +400,14 @@ def _define_run_frames(
399400
self.start, self.stop, self.step = start, stop, step
400401
return slicer
401402

402-
def _prepare_sliced_trajectory(self, slicer: Union[slice, np.ndarray]):
403+
def _prepare_sliced_trajectory(self, slicer: slice | np.ndarray):
403404
"""Prepares sliced trajectory for use in subsequent parallel computations:
404405
namely, assigns self._sliced_trajectory and its appropriate attributes,
405406
self.n_frames, self.frames and self.times.
406407
407408
Parameters
408409
----------
409-
slicer : Union[slice, np.ndarray]
410+
slicer : slice or numpy.ndarray
410411
appropriate slicer for the trajectory
411412
412413
@@ -511,7 +512,7 @@ def _conclude(self):
511512
def _compute(
512513
self,
513514
indexed_frames: np.ndarray,
514-
verbose: bool = None,
515+
verbose: bool | None = None,
515516
*,
516517
progressbar_kwargs=None,
517518
) -> "AnalysisBase":
@@ -520,8 +521,8 @@ def _compute(
520521
521522
Parameters
522523
----------
523-
indexed_frames : np.ndarray
524-
np.ndarray of (n, 2) shape, where first column is frame iteration
524+
indexed_frames : numpy.ndarray
525+
numpy.ndarray of (n, 2) shape, where first column is frame iteration
525526
indices and second is frame numbers
526527
527528
verbose : bool, optional
@@ -567,10 +568,10 @@ def _compute(
567568
def _setup_computation_groups(
568569
self,
569570
n_parts: int,
570-
start: int = None,
571-
stop: int = None,
572-
step: int = None,
573-
frames: Union[slice, np.ndarray] = None,
571+
start: int | None = None,
572+
stop: int | None = None,
573+
step: int | None = None,
574+
frames: slice | np.ndarray | None = None,
574575
) -> list[np.ndarray]:
575576
"""
576577
Splits the trajectory frames, defined by ``start/stop/step`` or
@@ -600,7 +601,7 @@ def _setup_computation_groups(
600601
601602
Returns
602603
-------
603-
computation_groups : list[np.ndarray]
604+
computation_groups : list[numpy.ndarray]
604605
list of (n, 2) shaped np.ndarrays with frame indices and numbers
605606
606607
@@ -638,7 +639,7 @@ def _setup_computation_groups(
638639

639640
def _configure_backend(
640641
self,
641-
backend: Union[str, BackendBase],
642+
backend: DefaultBackendOptions | BackendBase,
642643
n_workers: int,
643644
unsupported_backend: bool = False,
644645
) -> BackendBase:
@@ -648,7 +649,7 @@ def _configure_backend(
648649
649650
Parameters
650651
----------
651-
backend : Union[str, BackendBase]
652+
backend : str or BackendBase
652653
backend to be used:
653654
- ``str`` is matched to a builtin backend (one of "serial",
654655
"multiprocessing" and "dask")
@@ -758,14 +759,14 @@ def _configure_backend(
758759

759760
def run(
760761
self,
761-
start: int = None,
762-
stop: int = None,
763-
step: int = None,
764-
frames: Iterable = None,
765-
verbose: bool = None,
766-
n_workers: int = None,
767-
n_parts: int = None,
768-
backend: Union[str, BackendBase] = None,
762+
start: int | None = None,
763+
stop: int | None = None,
764+
step: int | None = None,
765+
frames: Iterable | None = None,
766+
verbose: bool | None = None,
767+
n_workers: int | None = None,
768+
n_parts: int | None = None,
769+
backend: DefaultBackendOptions | BackendBase | None = None,
769770
*,
770771
unsupported_backend: bool = False,
771772
progressbar_kwargs=None,
@@ -796,15 +797,15 @@ def run(
796797
ProgressBar keywords with custom parameters regarding progress bar
797798
position, etc; see :class:`MDAnalysis.lib.log.ProgressBar`
798799
for full list. Available only for ``backend='serial'``
799-
backend : Union[str, BackendBase], optional
800+
backend : str or BackendBase, optional
800801
By default, performs calculations in a serial fashion.
801802
Otherwise, user can choose a backend: ``str`` is matched to a
802803
builtin backend (one of ``serial``, ``multiprocessing`` and
803804
``dask``), or a :class:`MDAnalysis.analysis.results.BackendBase`
804805
subclass.
805806
806807
.. versionadded:: 2.8.0
807-
n_workers : int
808+
n_workers : int, optional
808809
positive integer with number of workers (processes, in case of
809810
built-in backends) to split the work between
810811

‎package/MDAnalysis/analysis/dssp/dssp.py‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -145,13 +145,13 @@
145145
"""
146146

147147
import warnings
148-
from typing import Optional, Union
149148

150149
import numpy as np
151150

152151
from MDAnalysis import AtomGroup, Universe
153152

154153
from ...due import Doi, due
154+
from ...lib.distances import DistanceBackendOptions
155155
from ..base import AnalysisBase, ResultsGroup
156156

157157
due.cite(
@@ -210,7 +210,7 @@ class DSSP(AnalysisBase):
210210
211211
Parameters
212212
----------
213-
atoms : Union[Universe, AtomGroup]
213+
atoms : Universe or AtomGroup
214214
input Universe or AtomGroup with at least 6 protein residues. In both cases, only protein residues will
215215
be chosen prior to the analysis via `select_atoms('protein')`.
216216
Heavy atoms of the protein are then selected by name
@@ -237,7 +237,7 @@ class DSSP(AnalysisBase):
237237
(e.g., a :exc:`ValueError` is raised) you must customize `hydrogen_name`
238238
for your specific case.
239239
240-
backend : str, optional
240+
backend : {'serial', 'OpenMP', 'distopia'}, optional
241241
:ref:`Backend for distance calculations<selection-of-acceleration-backend>`, by default ``"serial"``.
242242
Can be set to ``"distopia"`` if `distopia`_ is installed.
243243
@@ -312,12 +312,12 @@ def get_supported_backends(cls):
312312

313313
def __init__(
314314
self,
315-
atoms: Union[Universe, AtomGroup],
315+
atoms: Universe | AtomGroup,
316316
guess_hydrogens: bool = True,
317317
*,
318-
heavyatom_names: tuple[str] = ("N", "CA", "C", "O O1 OT1"),
318+
heavyatom_names: tuple[str, ...] = ("N", "CA", "C", "O O1 OT1"),
319319
hydrogen_name: str = "H HN HT1 HT2 HT3",
320-
backend: str = "serial",
320+
backend: DistanceBackendOptions = "serial",
321321
):
322322
self._guess_hydrogens = guess_hydrogens
323323
self._backend = backend
@@ -335,7 +335,7 @@ def __init__(
335335
]
336336
for t in heavyatom_names
337337
}
338-
self._donor_mask: Optional[np.ndarray] = ag.residues.resnames != "PRO"
338+
self._donor_mask: np.ndarray | None = ag.residues.resnames != "PRO"
339339
self._box = self._trajectory.ts.dimensions
340340
if self._box is not None and np.allclose(
341341
self._box, [1, 1, 1, 90, 90, 90]
@@ -394,7 +394,7 @@ def _get_coords(self) -> np.ndarray:
394394
395395
Returns
396396
-------
397-
np.ndarray
397+
numpy.ndarray
398398
coordinates of (N,CA,C,O,H) atoms
399399
400400
Raises
@@ -474,12 +474,12 @@ def translate(onehot: np.ndarray) -> np.ndarray:
474474
475475
Parameters
476476
----------
477-
onehot : np.ndarray
477+
onehot : numpy.ndarray
478478
input array of one-hot encoding in ('-', 'H', 'E') order
479479
480480
Returns
481481
-------
482-
np.ndarray
482+
numpy.ndarray
483483
array of '-', 'H' and 'E' symbols with secondary structure
484484
485485

0 commit comments

Comments
 (0)