Skip to content

Commit 03c0c20

Browse files
committed
Fixes linting errors
1 parent 1c4cab8 commit 03c0c20

22 files changed

+135
-128
lines changed

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ ignore = ["SIM103", # needless bool
4646
"D105", # undocumented __init__
4747
"D107", # undocumented magic method
4848
"D203", # blank line before class docstring
49-
"D213"] # multi line summary should start at second line
49+
"D213", # multi line summary should start at second line
50+
"UP038"] # non pep604 isinstance - to be removed
5051

5152
# ignore docstring lints in the tests and install script
5253
[tool.ruff.lint.per-file-ignores]

ratapi/classlist.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import importlib
66
import warnings
77
from collections.abc import Sequence
8-
from typing import Any, Generic, TypeVar, Union
8+
from typing import Any, Generic, TypeVar
99

1010
import numpy as np
1111
import prettytable
@@ -38,7 +38,7 @@ class ClassList(collections.UserList, Generic[T]):
3838
3939
"""
4040

41-
def __init__(self, init_list: Union[Sequence[T], T] = None, name_field: str = "name") -> None:
41+
def __init__(self, init_list: Sequence[T] | T = None, name_field: str = "name") -> None:
4242
self.name_field = name_field
4343

4444
# Set input as list if necessary
@@ -114,7 +114,7 @@ def __str__(self):
114114
output = str(self.data)
115115
return output
116116

117-
def __getitem__(self, index: Union[int, slice, str, T]) -> T:
117+
def __getitem__(self, index: int | slice | str | T) -> T:
118118
"""Get an item by its index, name, a slice, or the object itself."""
119119
if isinstance(index, (int, slice)):
120120
return self.data[index]
@@ -262,12 +262,12 @@ def insert(self, index: int, obj: T = None, **kwargs) -> None:
262262
self._validate_name_field(kwargs)
263263
self.data.insert(index, self._class_handle(**kwargs))
264264

265-
def remove(self, item: Union[T, str]) -> None:
265+
def remove(self, item: T | str) -> None:
266266
"""Remove an object from the ClassList using either the object itself or its ``name_field`` value."""
267267
item = self._get_item_from_name_field(item)
268268
self.data.remove(item)
269269

270-
def count(self, item: Union[T, str]) -> int:
270+
def count(self, item: T | str) -> int:
271271
"""Return the number of times an object appears in the ClassList.
272272
273273
This method can use either the object itself or its ``name_field`` value.
@@ -276,7 +276,7 @@ def count(self, item: Union[T, str]) -> int:
276276
item = self._get_item_from_name_field(item)
277277
return self.data.count(item)
278278

279-
def index(self, item: Union[T, str], offset: bool = False, *args) -> int:
279+
def index(self, item: T | str, offset: bool = False, *args) -> int:
280280
"""Return the index of a particular object in the ClassList.
281281
282282
This method can use either the object itself or its ``name_field`` value.
@@ -309,7 +309,7 @@ def union(self, other: Sequence[T]) -> None:
309309
]
310310
)
311311

312-
def set_fields(self, index: Union[int, slice, str, T], **kwargs) -> None:
312+
def set_fields(self, index: int | slice | str | T, **kwargs) -> None:
313313
"""Assign the values of an existing object's attributes using keyword arguments."""
314314
self._validate_name_field(kwargs)
315315
pydantic_object = False
@@ -519,7 +519,7 @@ def _check_classes(self, input_list: Sequence[T]) -> None:
519519
f"In the input list:\n{newline.join(error for error in error_list)}\n"
520520
)
521521

522-
def _get_item_from_name_field(self, value: Union[T, str]) -> Union[T, str]:
522+
def _get_item_from_name_field(self, value: T | str) -> T | str:
523523
"""Return the object with the given value of the ``name_field`` attribute in the ClassList.
524524
525525
Parameters
@@ -577,11 +577,12 @@ def _determine_class_handle(input_list: Sequence[T]):
577577
@classmethod
578578
def __get_pydantic_core_schema__(cls, source: Any, handler):
579579
# import here so that the ClassList can be instantiated and used without Pydantic installed
580+
from typing import get_args, get_origin
581+
580582
from pydantic import ValidatorFunctionWrapHandler
581583
from pydantic.types import (
582584
core_schema, # import core_schema through here rather than making pydantic_core a dependency
583585
)
584-
from typing_extensions import get_args, get_origin
585586

586587
# if annotated with a class, get the item type of that class
587588
origin = get_origin(source)

ratapi/controls.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import tempfile
66
import warnings
77
from pathlib import Path
8-
from typing import Union
98

109
import prettytable
1110
from pydantic import (
@@ -233,7 +232,7 @@ def delete_IPC(self):
233232
os.remove(self._IPCFilePath)
234233
return None
235234

236-
def save(self, filepath: Union[str, Path] = "./controls.json"):
235+
def save(self, filepath: str | Path = "./controls.json"):
237236
"""Save a controls object to a JSON file.
238237
239238
Parameters
@@ -245,7 +244,7 @@ def save(self, filepath: Union[str, Path] = "./controls.json"):
245244
filepath.write_text(self.model_dump_json())
246245

247246
@classmethod
248-
def load(cls, path: Union[str, Path]) -> "Controls":
247+
def load(cls, path: str | Path) -> "Controls":
249248
"""Load a controls object from file.
250249
251250
Parameters

ratapi/events.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
"""Hooks for connecting to run callback events."""
22

33
import os
4-
from typing import Callable, Union
4+
from collections.abc import Callable
55

66
from ratapi.rat_core import EventBridge, EventTypes, PlotEventData, ProgressEventData
77

88

9-
def notify(event_type: EventTypes, data: Union[str, PlotEventData, ProgressEventData]) -> None:
9+
def notify(event_type: EventTypes, data: str | PlotEventData | ProgressEventData) -> None:
1010
"""Call registered callbacks with data when event type has been triggered.
1111
1212
Parameters
@@ -22,7 +22,7 @@ def notify(event_type: EventTypes, data: Union[str, PlotEventData, ProgressEvent
2222
callback(data)
2323

2424

25-
def get_event_callback(event_type: EventTypes) -> list[Callable[[Union[str, PlotEventData, ProgressEventData]], None]]:
25+
def get_event_callback(event_type: EventTypes) -> list[Callable[[str | PlotEventData | ProgressEventData], None]]:
2626
"""Return all callbacks registered for the given event type.
2727
2828
Parameters
@@ -39,7 +39,7 @@ def get_event_callback(event_type: EventTypes) -> list[Callable[[Union[str, Plot
3939
return list(__event_callbacks[event_type])
4040

4141

42-
def register(event_type: EventTypes, callback: Callable[[Union[str, PlotEventData, ProgressEventData]], None]) -> None:
42+
def register(event_type: EventTypes, callback: Callable[[str | PlotEventData | ProgressEventData], None]) -> None:
4343
"""Register a new callback for the event type.
4444
4545
Parameters

ratapi/inputs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import importlib
44
import os
55
import pathlib
6-
from typing import Callable, Union
6+
from collections.abc import Callable
77

88
import numpy as np
99

@@ -23,7 +23,7 @@
2323
}
2424

2525

26-
def get_python_handle(file_name: str, function_name: str, path: Union[str, pathlib.Path] = "") -> Callable:
26+
def get_python_handle(file_name: str, function_name: str, path: str | pathlib.Path = "") -> Callable:
2727
"""Get the function handle from a function defined in a python module located anywhere within the filesystem.
2828
2929
Parameters

ratapi/outputs.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import json
44
from dataclasses import dataclass
55
from pathlib import Path
6-
from typing import Any, Optional, Union
6+
from typing import Any, Union
77

88
import numpy as np
99

@@ -244,7 +244,7 @@ def __str__(self):
244244
output += get_field_string(key, value, 100)
245245
return output
246246

247-
def save(self, filepath: Union[str, Path] = "./results.json"):
247+
def save(self, filepath: str | Path = "./results.json"):
248248
"""Save the Results object to a JSON file.
249249
250250
Parameters
@@ -258,7 +258,7 @@ def save(self, filepath: Union[str, Path] = "./results.json"):
258258
filepath.write_text(json.dumps(json_dict))
259259

260260
@classmethod
261-
def load(cls, path: Union[str, Path]) -> Union["Results", "BayesResults"]:
261+
def load(cls, path: str | Path) -> Union["Results", "BayesResults"]:
262262
"""Load a Results object from file.
263263
264264
Parameters
@@ -538,7 +538,7 @@ class BayesResults(Results):
538538
nestedSamplerOutput: NestedSamplerOutput
539539
chain: np.ndarray
540540

541-
def save(self, filepath: Union[str, Path] = "./results.json"):
541+
def save(self, filepath: str | Path = "./results.json"):
542542
"""Save the BayesResults object to a JSON file.
543543
544544
Parameters
@@ -574,7 +574,7 @@ def save(self, filepath: Union[str, Path] = "./results.json"):
574574
filepath.write_text(json.dumps(json_dict))
575575

576576

577-
def write_core_results_fields(results: Union[Results, BayesResults], json_dict: Optional[dict] = None) -> dict:
577+
def write_core_results_fields(results: Results | BayesResults, json_dict: dict | None = None) -> dict:
578578
"""Modify the values of the fields that appear in both Results and BayesResults when saving to a json file.
579579
580580
Parameters
@@ -684,8 +684,8 @@ def read_bayes_results_fields(results_dict: dict) -> dict:
684684
def make_results(
685685
procedure: Procedures,
686686
output_results: ratapi.rat_core.OutputResult,
687-
bayes_results: Optional[ratapi.rat_core.OutputBayesResult] = None,
688-
) -> Union[Results, BayesResults]:
687+
bayes_results: ratapi.rat_core.OutputBayesResult | None = None,
688+
) -> Results | BayesResults:
689689
"""Initialise a python Results or BayesResults object using the outputs from a RAT calculation.
690690
691691
Parameters

ratapi/project.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
import functools
66
import json
77
import warnings
8+
from collections.abc import Callable
89
from enum import Enum
910
from pathlib import Path
1011
from textwrap import indent
11-
from typing import Annotated, Any, Callable, Union
12+
from typing import Annotated, Any, get_args, get_origin
1213

1314
import numpy as np
1415
from pydantic import (
@@ -21,7 +22,6 @@
2122
field_validator,
2223
model_validator,
2324
)
24-
from typing_extensions import get_args, get_origin
2525

2626
import ratapi.models
2727
from ratapi.classlist import ClassList
@@ -248,10 +248,10 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute
248248
data: ClassList[ratapi.models.Data] = ClassList()
249249
"""Experimental data for a model."""
250250

251-
layers: Union[
252-
Annotated[ClassList[ratapi.models.Layer], Tag("no_abs")],
253-
Annotated[ClassList[ratapi.models.AbsorptionLayer], Tag("abs")],
254-
] = Field(
251+
layers: (
252+
Annotated[ClassList[ratapi.models.Layer], Tag("no_abs")]
253+
| Annotated[ClassList[ratapi.models.AbsorptionLayer], Tag("abs")]
254+
) = Field(
255255
default=ClassList(),
256256
discriminator=Discriminator(
257257
discriminate_layers,
@@ -265,10 +265,10 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute
265265
domain_contrasts: ClassList[ratapi.models.DomainContrast] = ClassList()
266266
"""The groups of layers required by each domain in a domains model."""
267267

268-
contrasts: Union[
269-
Annotated[ClassList[ratapi.models.Contrast], Tag("no_ratio")],
270-
Annotated[ClassList[ratapi.models.ContrastWithRatio], Tag("ratio")],
271-
] = Field(
268+
contrasts: (
269+
Annotated[ClassList[ratapi.models.Contrast], Tag("no_ratio")]
270+
| Annotated[ClassList[ratapi.models.ContrastWithRatio], Tag("ratio")]
271+
) = Field(
272272
default=ClassList(),
273273
discriminator=Discriminator(
274274
discriminate_contrasts,
@@ -577,7 +577,7 @@ def update_renamed_models(self) -> "Project":
577577
old_names = self._all_names[class_list]
578578
new_names = getattr(self, class_list).get_names()
579579
if len(old_names) == len(new_names):
580-
name_diff = [(old, new) for (old, new) in zip(old_names, new_names) if old != new]
580+
name_diff = [(old, new) for (old, new) in zip(old_names, new_names, strict=False) if old != new]
581581
for old_name, new_name in name_diff:
582582
for field in fields_to_update:
583583
project_field = getattr(self, field.attribute)
@@ -927,7 +927,7 @@ def classlist_script(name, classlist):
927927
+ "\n)"
928928
)
929929

930-
def save(self, filepath: Union[str, Path] = "./project.json"):
930+
def save(self, filepath: str | Path = "./project.json"):
931931
"""Save a project to a JSON file.
932932
933933
Parameters
@@ -973,7 +973,7 @@ def make_custom_file_dict(item):
973973
filepath.write_text(json.dumps(json_dict))
974974

975975
@classmethod
976-
def load(cls, path: Union[str, Path]) -> "Project":
976+
def load(cls, path: str | Path) -> "Project":
977977
"""Load a project from file.
978978
979979
Parameters

ratapi/utils/convert.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from collections.abc import Iterable
55
from os import PathLike
66
from pathlib import Path
7-
from typing import Union
87

98
from numpy import array, empty
109
from scipy.io.matlab import MatlabOpaque, loadmat
@@ -15,7 +14,7 @@
1514
from ratapi.utils.enums import Geometries, Languages, LayerModels
1615

1716

18-
def r1_to_project(filename: Union[str, PathLike]) -> Project:
17+
def r1_to_project(filename: str | PathLike) -> Project:
1918
"""Read a RasCAL1 project struct as a Python `Project`.
2019
2120
Parameters
@@ -43,7 +42,7 @@ def r1_to_project(filename: Union[str, PathLike]) -> Project:
4342
layer_model = LayerModels.CustomXY
4443
layer_model = LayerModels(layer_model)
4544

46-
def zip_if_several(*params) -> Union[tuple, list[tuple]]:
45+
def zip_if_several(*params) -> tuple | list[tuple]:
4746
"""Zips parameters if necessary, but can handle single-item parameters.
4847
4948
Examples
@@ -64,7 +63,7 @@ def zip_if_several(*params) -> Union[tuple, list[tuple]]:
6463
6564
"""
6665
if all(isinstance(param, Iterable) and not isinstance(param, str) for param in params):
67-
return zip(*params)
66+
return zip(*params, strict=False)
6867
return [params]
6968

7069
def read_param(names, constrs, values, fits):
@@ -319,8 +318,8 @@ def fix_invalid_constraints(name: str, constrs: tuple[float, float], value: floa
319318

320319

321320
def project_to_r1(
322-
project: Project, filename: Union[str, PathLike] = "RAT_project", return_struct: bool = False
323-
) -> Union[dict, None]:
321+
project: Project, filename: str | PathLike = "RAT_project", return_struct: bool = False
322+
) -> dict | None:
324323
"""Convert a RAT Project to a RasCAL1 project struct.
325324
326325
Parameters

ratapi/utils/custom_errors.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
"""Defines routines for custom error handling in RAT."""
22

3-
from typing import Optional
4-
53
import pydantic_core
64

75

86
def custom_pydantic_validation_error(
97
error_list: list[pydantic_core.ErrorDetails],
10-
custom_error_msgs: Optional[dict[str, str]] = None,
8+
custom_error_msgs: dict[str, str] | None = None,
119
) -> list[pydantic_core.ErrorDetails]:
1210
"""Give Pydantic errors a better custom message with extraneous information removed.
1311

ratapi/utils/enums.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
"""The Enum values used in the parameters of various ratapi classes and functions."""
22

3-
from typing import Union
4-
53
try:
64
from enum import StrEnum
75
except ImportError:
@@ -92,7 +90,7 @@ class Strategies(RATEnum):
9290
or a pure recombination of parent parameter values."""
9391

9492
@classmethod
95-
def _missing_(cls, value: Union[int, str]):
93+
def _missing_(cls, value: int | str):
9694
# legacy compatibility with strategies being 1-indexed ints under the hood
9795
if isinstance(value, int):
9896
if value < 1 or value > 6:

0 commit comments

Comments
 (0)