From 2cc465a9caa2e70f7ed3f0ff1698b6b61a687f26 Mon Sep 17 00:00:00 2001 From: Gabriel Gerlero Date: Thu, 17 Oct 2024 20:04:32 -0300 Subject: [PATCH 1/3] Enable extra Ruff rules --- pyproject.toml | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 506deac..48f7532 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -87,7 +87,36 @@ packages = [ strict = true [tool.ruff.lint] -extend-select = ["D", "I", "RUF", "UP"] +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", +] [tool.ruff.lint.pydocstyle] convention = "pep257" From 8579acf91c346ce6f126b201a972561644bba656 Mon Sep 17 00:00:00 2001 From: Gabriel Gerlero Date: Thu, 17 Oct 2024 20:09:00 -0300 Subject: [PATCH 2/3] Apply extra Ruff rules --- foamlib/_cases/_async.py | 9 +++++---- foamlib/_cases/_base.py | 15 ++++++++------- foamlib/_cases/_run.py | 8 ++------ foamlib/_cases/_slurm.py | 6 ++++-- foamlib/_cases/_subprocess.py | 8 +++++--- foamlib/_cases/_sync.py | 11 +++++------ foamlib/_files/_base.py | 10 ++++------ foamlib/_files/_files.py | 9 +++------ foamlib/_files/_io.py | 8 +++++--- foamlib/_files/_serialization.py | 32 +++++++++++++++----------------- tests/test_files/test_files.py | 5 ++--- 11 files changed, 58 insertions(+), 63 deletions(-) diff --git a/foamlib/_cases/_async.py b/foamlib/_cases/_async.py index d85c5f4..d927580 100644 --- a/foamlib/_cases/_async.py +++ b/foamlib/_cases/_async.py @@ -1,9 +1,8 @@ import asyncio import multiprocessing -import os import sys from contextlib import asynccontextmanager -from typing import Any, Callable, Optional, TypeVar, Union, overload +from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union, overload if sys.version_info >= (3, 9): from collections.abc import ( @@ -29,6 +28,9 @@ from ._subprocess import run_async from ._util import ValuedGenerator, awaitableasynccontextmanager +if TYPE_CHECKING: + import os + X = TypeVar("X") Y = TypeVar("Y") @@ -138,8 +140,7 @@ def __getitem__( ret = super().__getitem__(index) if isinstance(ret, FoamCaseBase.TimeDirectory): return AsyncFoamCase.TimeDirectory(ret) - else: - return [AsyncFoamCase.TimeDirectory(r) for r in ret] + return [AsyncFoamCase.TimeDirectory(r) for r in ret] async def run( self, diff --git a/foamlib/_cases/_base.py b/foamlib/_cases/_base.py index bec3307..63648e1 100644 --- a/foamlib/_cases/_base.py +++ b/foamlib/_cases/_base.py @@ -1,8 +1,8 @@ -import os import shutil import sys from pathlib import Path from typing import ( + TYPE_CHECKING, Optional, Union, overload, @@ -23,6 +23,9 @@ from .._files import FoamFieldFile, FoamFile +if TYPE_CHECKING: + import os + class FoamCaseBase(Sequence["FoamCaseBase.TimeDirectory"]): def __init__(self, path: Union["os.PathLike[str]", str] = Path()): @@ -57,18 +60,16 @@ def name(self) -> str: def __getitem__(self, key: str) -> FoamFieldFile: if (self.path / f"{key}.gz").is_file() and not (self.path / key).is_file(): return FoamFieldFile(self.path / f"{key}.gz") - else: - return FoamFieldFile(self.path / key) + return FoamFieldFile(self.path / key) def __contains__(self, obj: object) -> bool: if isinstance(obj, FoamFieldFile): return obj.path.parent == self.path and obj.path.is_file() - elif isinstance(obj, str): + if isinstance(obj, str): return (self.path / obj).is_file() or ( self.path / f"{obj}.gz" ).is_file() - else: - return False + return False def __iter__(self) -> Iterator[FoamFieldFile]: for p in self.path.iterdir(): @@ -124,7 +125,7 @@ def __getitem__( ) -> Union["FoamCaseBase.TimeDirectory", Sequence["FoamCaseBase.TimeDirectory"]]: if isinstance(index, str): return FoamCaseBase.TimeDirectory(self.path / index) - elif isinstance(index, float): + if isinstance(index, float): for time in self._times: if time.time == index: return time diff --git a/foamlib/_cases/_run.py b/foamlib/_cases/_run.py index 30ec8ac..dbd498a 100644 --- a/foamlib/_cases/_run.py +++ b/foamlib/_cases/_run.py @@ -256,8 +256,7 @@ def __env(self, *, shell: bool) -> Optional[Mapping[str, str]]: env["DYLD_LIBRARY_PATH"] = env["FOAM_LD_LIBRARY_PATH"] return env - else: - return None + return None @contextmanager def __output( @@ -267,10 +266,7 @@ def __output( if isinstance(cmd, str): name = shlex.split(cmd)[0] else: - if isinstance(cmd[0], os.PathLike): - name = Path(cmd[0]).name - else: - name = cmd[0] + name = Path(cmd[0]).name if isinstance(cmd[0], os.PathLike) else cmd[0] with (self.path / f"log.{name}").open("ab") as stdout: yield stdout, STDOUT diff --git a/foamlib/_cases/_slurm.py b/foamlib/_cases/_slurm.py index 71751d0..edb5529 100644 --- a/foamlib/_cases/_slurm.py +++ b/foamlib/_cases/_slurm.py @@ -1,7 +1,6 @@ -import os import shutil import sys -from typing import Any, Optional, Union +from typing import TYPE_CHECKING, Any, Optional, Union if sys.version_info >= (3, 9): from collections.abc import Sequence @@ -11,6 +10,9 @@ from ._async import AsyncFoamCase from ._subprocess import run_async +if TYPE_CHECKING: + import os + class AsyncSlurmFoamCase(AsyncFoamCase): """An asynchronous OpenFOAM case that launches jobs on a Slurm cluster.""" diff --git a/foamlib/_cases/_subprocess.py b/foamlib/_cases/_subprocess.py index 78fe33f..88d24d6 100644 --- a/foamlib/_cases/_subprocess.py +++ b/foamlib/_cases/_subprocess.py @@ -1,9 +1,11 @@ import asyncio -import os import subprocess import sys from io import BytesIO -from typing import IO, Optional, Union +from typing import IO, TYPE_CHECKING, Optional, Union + +if TYPE_CHECKING: + import os if sys.version_info >= (3, 9): from collections.abc import Mapping, Sequence @@ -18,7 +20,7 @@ def __str__(self) -> str: if self.stderr: if isinstance(self.stderr, bytes): return super().__str__() + "\n" + self.stderr.decode() - elif isinstance(self.stderr, str): + if isinstance(self.stderr, str): return super().__str__() + "\n" + self.stderr return super().__str__() diff --git a/foamlib/_cases/_sync.py b/foamlib/_cases/_sync.py index c77c9c2..12a9e97 100644 --- a/foamlib/_cases/_sync.py +++ b/foamlib/_cases/_sync.py @@ -1,8 +1,7 @@ -import os import shutil import sys from types import TracebackType -from typing import Any, Callable, Optional, Type, Union, overload +from typing import TYPE_CHECKING, Any, Callable, Optional, Type, Union, overload if sys.version_info >= (3, 9): from collections.abc import Collection, Sequence @@ -20,6 +19,9 @@ from ._subprocess import run_sync from ._util import ValuedGenerator +if TYPE_CHECKING: + import os + class FoamCase(FoamCaseRunBase): """ @@ -44,8 +46,6 @@ def cell_centers(self) -> FoamFieldFile: for _ in calls: pass - print(calls.value) - return calls.value @staticmethod @@ -89,8 +89,7 @@ def __getitem__( ret = super().__getitem__(index) if isinstance(ret, FoamCaseBase.TimeDirectory): return FoamCase.TimeDirectory(ret) - else: - return [FoamCase.TimeDirectory(r) for r in ret] + return [FoamCase.TimeDirectory(r) for r in ret] def __enter__(self) -> Self: return self diff --git a/foamlib/_files/_base.py b/foamlib/_files/_base.py index ecec91c..bca60b7 100644 --- a/foamlib/_files/_base.py +++ b/foamlib/_files/_base.py @@ -1,17 +1,15 @@ import sys from dataclasses import dataclass -from typing import Dict, NamedTuple, Optional, Tuple, Union +from typing import TYPE_CHECKING, Dict, NamedTuple, Optional, Tuple, Union + +if TYPE_CHECKING: + import numpy as np if sys.version_info >= (3, 9): from collections.abc import Mapping, Sequence else: from typing import Mapping, Sequence -try: - import numpy as np -except ModuleNotFoundError: - pass - class FoamFileBase: class DimensionSet(NamedTuple): diff --git a/foamlib/_files/_files.py b/foamlib/_files/_files.py index 8f4b1ee..fde7b72 100644 --- a/foamlib/_files/_files.py +++ b/foamlib/_files/_files.py @@ -1,5 +1,5 @@ import sys -from typing import Any, Optional, Tuple, Union, cast +from typing import TYPE_CHECKING, Any, Optional, Tuple, Union, cast if sys.version_info >= (3, 8): from typing import Literal @@ -16,10 +16,8 @@ from ._serialization import Kind, dumpb from ._util import is_sequence -try: +if TYPE_CHECKING: import numpy as np -except ModuleNotFoundError: - pass class FoamFile( @@ -172,8 +170,7 @@ def __getitem__( if value is ...: return FoamFile.SubDict(self, keywords) - else: - return value + return value def __setitem__( self, keywords: Optional[Union[str, Tuple[str, ...]]], data: "FoamFile._SetData" diff --git a/foamlib/_files/_io.py b/foamlib/_files/_io.py index bc395f3..51cc85e 100644 --- a/foamlib/_files/_io.py +++ b/foamlib/_files/_io.py @@ -1,10 +1,10 @@ import gzip -import os import sys from copy import deepcopy from pathlib import Path from types import TracebackType from typing import ( + TYPE_CHECKING, Optional, Tuple, Type, @@ -18,6 +18,9 @@ from ._parsing import Parsed +if TYPE_CHECKING: + import os + class FoamFileIO: def __init__(self, path: Union["os.PathLike[str]", str]) -> None: @@ -63,8 +66,7 @@ def _read(self, *, missing_ok: bool = False) -> Tuple[bytes, Parsed]: if self.__contents is None: if missing_ok: return b"", Parsed(b"") - else: - raise FileNotFoundError(self.path) + raise FileNotFoundError(self.path) if self.__parsed is None: parsed = Parsed(self.__contents) diff --git a/foamlib/_files/_serialization.py b/foamlib/_files/_serialization.py index 110a6e9..5362229 100644 --- a/foamlib/_files/_serialization.py +++ b/foamlib/_files/_serialization.py @@ -35,7 +35,7 @@ def dumpb( if numpy and isinstance(data, np.ndarray): return dumpb(data.tolist(), kind=kind) - elif isinstance(data, Mapping): + if isinstance(data, Mapping): entries = [] for k, v in data.items(): b = dumpb(v, kind=kind) @@ -48,12 +48,12 @@ def dumpb( return b" ".join(entries) - elif isinstance(data, FoamFileBase.DimensionSet) or ( + if isinstance(data, FoamFileBase.DimensionSet) or ( kind == Kind.DIMENSIONS and is_sequence(data) and len(data) == 7 ): return b"[" + b" ".join(dumpb(v) for v in data) + b"]" - elif (kind == Kind.FIELD or kind == Kind.BINARY_FIELD) and ( + if (kind == Kind.FIELD or kind == Kind.BINARY_FIELD) and ( isinstance(data, (int, float)) or is_sequence(data) and data @@ -62,7 +62,7 @@ def dumpb( ): return b"uniform " + dumpb(data, kind=Kind.SINGLE_ENTRY) - elif (kind == Kind.FIELD or kind == Kind.BINARY_FIELD) and is_sequence(data): + if (kind == Kind.FIELD or kind == Kind.BINARY_FIELD) and is_sequence(data): if isinstance(data[0], (int, float)): tensor_kind = b"scalar" elif len(data[0]) == 3: @@ -88,10 +88,10 @@ def dumpb( return b"nonuniform List<" + tensor_kind + b"> " + dumpb(len(data)) + contents - elif kind != Kind.SINGLE_ENTRY and isinstance(data, tuple): + if kind != Kind.SINGLE_ENTRY and isinstance(data, tuple): return b" ".join(dumpb(v) for v in data) - elif isinstance(data, FoamFileBase.Dimensioned): + if isinstance(data, FoamFileBase.Dimensioned): if data.name is not None: return ( dumpb(data.name) @@ -100,20 +100,18 @@ def dumpb( + b" " + dumpb(data.value, kind=Kind.SINGLE_ENTRY) ) - else: - return ( - dumpb(data.dimensions, kind=Kind.DIMENSIONS) - + b" " - + dumpb(data.value, kind=Kind.SINGLE_ENTRY) - ) + return ( + dumpb(data.dimensions, kind=Kind.DIMENSIONS) + + b" " + + dumpb(data.value, kind=Kind.SINGLE_ENTRY) + ) - elif is_sequence(data): + if is_sequence(data): return b"(" + b" ".join(dumpb(v, kind=Kind.SINGLE_ENTRY) for v in data) + b")" - elif data is True: + if data is True: return b"yes" - elif data is False: + if data is False: return b"no" - else: - return str(data).encode("latin-1") + return str(data).encode("latin-1") diff --git a/tests/test_files/test_files.py b/tests/test_files/test_files.py index 5aafab3..4f83109 100644 --- a/tests/test_files/test_files.py +++ b/tests/test_files/test_files.py @@ -19,9 +19,8 @@ def test_write_read(tmp_path: Path) -> None: with pytest.raises(FileNotFoundError): d["key"] - with d: - with pytest.raises(FileNotFoundError): - d["key"] + with d, pytest.raises(FileNotFoundError): + d["key"] d[None] = "touch" assert len(d) == 1 From 186cef4bde542c37aea890906a774aebbd3eaed2 Mon Sep 17 00:00:00 2001 From: Gabriel Gerlero Date: Thu, 17 Oct 2024 20:10:56 -0300 Subject: [PATCH 3/3] Update .git-blame-ignore-revs --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index a3fb2e2..0c9045c 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,2 +1,5 @@ # Apply extra Ruff rules 5a858118ea3f7475545103fba8b045eca85e7d3d + +# Apply extra Ruff rules +8579acf91c346ce6f126b201a972561644bba656