Skip to content

Commit

Permalink
Merge pull request #247 from gerlero/ruff
Browse files Browse the repository at this point in the history
Apply extra Ruff rules
  • Loading branch information
gerlero authored Nov 2, 2024
2 parents d6ee256 + b3e8d55 commit c7cd976
Show file tree
Hide file tree
Showing 13 changed files with 87 additions and 76 deletions.
3 changes: 3 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@

# Apply extra Ruff rules
8579acf91c346ce6f126b201a972561644bba656

# Apply extra Ruff rules
520ba8c05d75e2510fa333ac086c2008ca6b4afb
5 changes: 4 additions & 1 deletion docs/ruff.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
extend = "../pyproject.toml"

[lint]
ignore = ["D"]
extend-ignore = [
"A001",
"D"
]
6 changes: 3 additions & 3 deletions foamlib/_cases/_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ async def cell_centers(self) -> FoamFieldFile:

max_cpus = multiprocessing.cpu_count()
"""
Maximum number of CPUs to use for running instances of `AsyncFoamCase` concurrently.
Maximum number of CPUs to use for running instances of `AsyncFoamCase` concurrently.
Defaults to the number of CPUs on the system.
"""

Expand Down Expand Up @@ -101,7 +101,7 @@ async def _run(

@staticmethod
async def _rmtree(
path: Union["os.PathLike[str]", str], ignore_errors: bool = False
path: Union["os.PathLike[str]", str], *, ignore_errors: bool = False
) -> None:
await aioshutil.rmtree(path, ignore_errors=ignore_errors)

Expand Down
22 changes: 13 additions & 9 deletions foamlib/_cases/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
from collections.abc import (
Iterator,
Sequence,
Set,
)
from collections.abc import Set as AbstractSet
else:
from typing import AbstractSet as Set
from typing import (
AbstractSet,
Iterator,
Sequence,
)
Expand All @@ -28,10 +28,10 @@


class FoamCaseBase(Sequence["FoamCaseBase.TimeDirectory"]):
def __init__(self, path: Union["os.PathLike[str]", str] = Path()):
def __init__(self, path: Union["os.PathLike[str]", str] = Path()) -> None:
self.path = Path(path).absolute()

class TimeDirectory(Set[FoamFieldFile]):
class TimeDirectory(AbstractSet[FoamFieldFile]):
"""
An OpenFOAM time directory in a case.
Expand All @@ -40,7 +40,7 @@ class TimeDirectory(Set[FoamFieldFile]):
:param path: The path to the time directory.
"""

def __init__(self, path: Union["os.PathLike[str]", str]):
def __init__(self, path: Union["os.PathLike[str]", str]) -> None:
self.path = Path(path).absolute()

@property
Expand Down Expand Up @@ -129,7 +129,8 @@ def __getitem__(
for time in self._times:
if time.time == index:
return time
raise IndexError(f"Time {index} not found")
msg = f"Time {index} not found"
raise IndexError(msg)
return self._times[index]

def __len__(self) -> int:
Expand All @@ -153,12 +154,14 @@ def _nsubdomains(self) -> Optional[int]:
try:
nsubdomains = self.decompose_par_dict["numberOfSubdomains"]
if not isinstance(nsubdomains, int):
raise TypeError(
msg = (
f"numberOfSubdomains in {self.decompose_par_dict} is not an integer"
)
return nsubdomains
raise TypeError(msg)
except FileNotFoundError:
return None
else:
return nsubdomains

@property
def _nprocessors(self) -> int:
Expand All @@ -170,7 +173,8 @@ def application(self) -> str:
"""The application name as set in the controlDict."""
application = self.control_dict["application"]
if not isinstance(application, str):
raise TypeError(f"application in {self.control_dict} is not a string")
msg = f"application in {self.control_dict} is not a string"
raise TypeError(msg)
return application

@property
Expand Down
21 changes: 9 additions & 12 deletions foamlib/_cases/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
Generator,
Mapping,
Sequence,
Set,
)
from collections.abc import Set as AbstractSet
else:
from typing import AbstractSet as Set
from typing import (
AbstractSet,
Callable,
Collection,
Coroutine,
Expand Down Expand Up @@ -155,7 +155,7 @@ def reconstruct_par(
def restore_0_dir(self) -> Union[None, Coroutine[None, None, None]]:
raise NotImplementedError

def __clean_paths(self) -> Set[Path]:
def __clean_paths(self) -> AbstractSet[Path]:
has_decompose_par_dict = (self.path / "system" / "decomposeParDict").is_file()
has_block_mesh_dict = (self.path / "system" / "blockMeshDict").is_file()

Expand Down Expand Up @@ -242,9 +242,8 @@ def __run_script(self, *, parallel: Optional[bool]) -> Optional[Path]:
elif parallel is False:
script = run if run.is_file() else all_run
else:
raise ValueError(
"Both (All)run and (All)run-parallel scripts are present. Please specify parallel argument."
)
msg = "Both (All)run and (All)run-parallel scripts are present. Please specify parallel argument."
raise ValueError(msg)
else:
script = run if run.is_file() else all_run
elif parallel is not False and (
Expand Down Expand Up @@ -420,9 +419,8 @@ def _run_calls(
cpus = self._nsubdomains
else:
cpus = 1
else:
if cpus is None:
cpus = 1
elif cpus is None:
cpus = 1

yield self.run(
[script_path], parallel=False, cpus=cpus, check=check, **kwargs
Expand Down Expand Up @@ -450,9 +448,8 @@ def _run_calls(

if cpus is None:
cpus = max(self._nprocessors, 1)
else:
if cpus is None:
cpus = 1
elif cpus is None:
cpus = 1

yield self.run(
[self.application],
Expand Down
4 changes: 2 additions & 2 deletions foamlib/_cases/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@


class ValuedGenerator(Generic[Y, S, R]):
def __init__(self, generator: Generator[Y, S, R]):
def __init__(self, generator: Generator[Y, S, R]) -> None:
self._generator = generator

def __iter__(self) -> Generator[Y, S, R]:
Expand All @@ -32,7 +32,7 @@ def __iter__(self) -> Generator[Y, S, R]:


class _AwaitableAsyncContextManager(Generic[R]):
def __init__(self, cm: "AsyncContextManager[R]"):
def __init__(self, cm: "AsyncContextManager[R]") -> None:
self._cm = cm

def __await__(self) -> Generator[Any, Any, R]:
Expand Down
32 changes: 21 additions & 11 deletions foamlib/_files/_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ def version(self) -> float:
"""Alias of `self["FoamFile", "version"]`."""
ret = self["FoamFile", "version"]
if not isinstance(ret, (int, float)):
raise TypeError("version is not a number")
msg = "version is not a number"
raise TypeError(msg)
return ret

@version.setter
Expand All @@ -109,9 +110,11 @@ def format(self) -> Literal["ascii", "binary"]:
"""Alias of `self["FoamFile", "format"]`."""
ret = self["FoamFile", "format"]
if not isinstance(ret, str):
raise TypeError("format is not a string")
msg = "format is not a string"
raise TypeError(msg)
if ret not in ("ascii", "binary"):
raise ValueError("format is not 'ascii' or 'binary'")
msg = "format is not 'ascii' or 'binary'"
raise ValueError(msg)
return cast(Literal["ascii", "binary"], ret)

@format.setter
Expand All @@ -123,7 +126,8 @@ def class_(self) -> str:
"""Alias of `self["FoamFile", "class"]`."""
ret = self["FoamFile", "class"]
if not isinstance(ret, str):
raise TypeError("class is not a string")
msg = "class is not a string"
raise TypeError(msg)
return ret

@class_.setter
Expand All @@ -135,7 +139,8 @@ def location(self) -> str:
"""Alias of `self["FoamFile", "location"]`."""
ret = self["FoamFile", "location"]
if not isinstance(ret, str):
raise TypeError("location is not a string")
msg = "location is not a string"
raise TypeError(msg)
return ret

@location.setter
Expand All @@ -147,7 +152,8 @@ def object_(self) -> str:
"""Alias of `self["FoamFile", "object"]`."""
ret = self["FoamFile", "object"]
if not isinstance(ret, str):
raise TypeError("object is not a string")
msg = "object is not a string"
raise TypeError(msg)
return ret

@object_.setter
Expand Down Expand Up @@ -213,7 +219,7 @@ def __setitem__(
kind = Kind.DIMENSIONS

if (
kind == Kind.FIELD or kind == Kind.BINARY_FIELD
kind in (Kind.FIELD, Kind.BINARY_FIELD)
) and self.class_ == "dictionary":
if not is_sequence(data):
class_ = "volScalarField"
Expand Down Expand Up @@ -352,7 +358,8 @@ def __getitem__(self, keyword: str) -> "FoamFieldFile.BoundarySubDict":
value = super().__getitem__(keyword)
if not isinstance(value, FoamFieldFile.BoundarySubDict):
assert not isinstance(value, FoamFile.SubDict)
raise TypeError(f"boundary {keyword} is not a dictionary")
msg = f"boundary {keyword} is not a dictionary"
raise TypeError(msg)
return value

class BoundarySubDict(FoamFile.SubDict):
Expand All @@ -363,7 +370,8 @@ def type(self) -> str:
"""Alias of `self["type"]`."""
ret = self["type"]
if not isinstance(ret, str):
raise TypeError("type is not a string")
msg = "type is not a string"
raise TypeError(msg)
return ret

@type.setter
Expand Down Expand Up @@ -412,7 +420,8 @@ def dimensions(self) -> Union[FoamFile.DimensionSet, Sequence[float]]:
"""Alias of `self["dimensions"]`."""
ret = self["dimensions"]
if not isinstance(ret, FoamFile.DimensionSet):
raise TypeError("dimensions is not a DimensionSet")
msg = "dimensions is not a DimensionSet"
raise TypeError(msg)
return ret

@dimensions.setter
Expand All @@ -439,7 +448,8 @@ def boundary_field(self) -> "FoamFieldFile.BoundariesSubDict":
ret = self["boundaryField"]
if not isinstance(ret, FoamFieldFile.BoundariesSubDict):
assert not isinstance(ret, FoamFile.SubDict)
raise TypeError("boundaryField is not a dictionary")
msg = "boundaryField is not a dictionary"
raise TypeError(msg)
return ret

@boundary_field.setter
Expand Down
8 changes: 4 additions & 4 deletions foamlib/_files/_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,14 @@ def _unpack_binary_field(

arr = array.array("d", "".join(tks).encode("latin-1"))

all: Union[Sequence[float], Sequence[Sequence[float]]]
values: Union[Sequence[float], Sequence[Sequence[float]]]

if elsize != 1:
all = [arr[i : i + elsize].tolist() for i in range(0, len(arr), elsize)]
values = [arr[i : i + elsize].tolist() for i in range(0, len(arr), elsize)]
else:
all = arr.tolist()
values = arr.tolist()

return [all]
return [values]


_IDENTCHARS = identchars + "$"
Expand Down
4 changes: 2 additions & 2 deletions foamlib/_files/_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def dumps(
):
return b"[" + b" ".join(dumps(v) for v in data) + b"]"

if (kind == Kind.FIELD or kind == Kind.BINARY_FIELD) and (
if kind in (Kind.FIELD, Kind.BINARY_FIELD) and (
isinstance(data, (int, float))
or is_sequence(data)
and data
Expand All @@ -62,7 +62,7 @@ def dumps(
):
return b"uniform " + dumps(data, kind=Kind.SINGLE_ENTRY)

if (kind == Kind.FIELD or kind == Kind.BINARY_FIELD) and is_sequence(data):
if kind in (Kind.FIELD, Kind.BINARY_FIELD) and is_sequence(data):
if isinstance(data[0], (int, float)):
tensor_kind = b"scalar"
elif len(data[0]) == 3:
Expand Down
48 changes: 19 additions & 29 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,35 +87,25 @@ packages = [
strict = true

[tool.ruff.lint]
extend-select = [
"ASYNC",
"B",
"C4",
"D",
"ERA",
"F",
"FLY",
"FURB",
"I",
"ICN",
"INT",
"NPY",
"PERF",
"PIE",
"PLC",
"PLE",
"PLW",
"PT",
"PTH",
"Q",
"RET",
"RSE",
"RUF",
"SIM",
"T20",
"TCH",
"UP",
"YTT",
extend-select = ["ALL"]
extend-ignore = [
"ANN401",
"ARG004",
"C901",
"COM812",
"E501",
"FA100",
"ISC001",
"PLR0911",
"PLR0912",
"PLR0913",
"PLR0915",
"PLR2004",
"PYI041",
"S101",
"S603",
"SLF001",
"TID252",
]

[tool.ruff.lint.pydocstyle]
Expand Down
6 changes: 5 additions & 1 deletion tests/ruff.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
extend = "../pyproject.toml"

[lint]
ignore = ["D"]
extend-ignore = [
"D",
"FBT003",
"N806",
]
Loading

0 comments on commit c7cd976

Please sign in to comment.