Skip to content

Commit

Permalink
Merge pull request #234 from gerlero/lint
Browse files Browse the repository at this point in the history
Apply extra Ruff rules
  • Loading branch information
gerlero authored Oct 17, 2024
2 parents 8ab5bb1 + 186cef4 commit 1ff15b8
Show file tree
Hide file tree
Showing 13 changed files with 91 additions and 64 deletions.
3 changes: 3 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
# Apply extra Ruff rules
5a858118ea3f7475545103fba8b045eca85e7d3d

# Apply extra Ruff rules
8579acf91c346ce6f126b201a972561644bba656
9 changes: 5 additions & 4 deletions foamlib/_cases/_async.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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")

Expand Down Expand Up @@ -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,
Expand Down
15 changes: 8 additions & 7 deletions foamlib/_cases/_base.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import os
import shutil
import sys
from pathlib import Path
from typing import (
TYPE_CHECKING,
Optional,
Union,
overload,
Expand All @@ -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()):
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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
Expand Down
8 changes: 2 additions & 6 deletions foamlib/_cases/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand Down
6 changes: 4 additions & 2 deletions foamlib/_cases/_slurm.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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."""
Expand Down
8 changes: 5 additions & 3 deletions foamlib/_cases/_subprocess.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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__()

Expand Down
11 changes: 5 additions & 6 deletions foamlib/_cases/_sync.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -20,6 +19,9 @@
from ._subprocess import run_sync
from ._util import ValuedGenerator

if TYPE_CHECKING:
import os


class FoamCase(FoamCaseRunBase):
"""
Expand All @@ -44,8 +46,6 @@ def cell_centers(self) -> FoamFieldFile:
for _ in calls:
pass

print(calls.value)

return calls.value

@staticmethod
Expand Down Expand Up @@ -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
Expand Down
10 changes: 4 additions & 6 deletions foamlib/_files/_base.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
9 changes: 3 additions & 6 deletions foamlib/_files/_files.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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"
Expand Down
8 changes: 5 additions & 3 deletions foamlib/_files/_io.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
32 changes: 15 additions & 17 deletions foamlib/_files/_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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")
31 changes: 30 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
5 changes: 2 additions & 3 deletions tests/test_files/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 1ff15b8

Please sign in to comment.