Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update type hints #243

Merged
merged 1 commit into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions foamlib/_files/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,38 @@

class FoamFileBase:
class DimensionSet(NamedTuple):
mass: Union[int, float] = 0
length: Union[int, float] = 0
time: Union[int, float] = 0
temperature: Union[int, float] = 0
moles: Union[int, float] = 0
current: Union[int, float] = 0
luminous_intensity: Union[int, float] = 0
mass: float = 0
length: float = 0
time: float = 0
temperature: float = 0
moles: float = 0
current: float = 0
luminous_intensity: float = 0

def __repr__(self) -> str:
return f"{type(self).__qualname__}({', '.join(f'{n}={v}' for n, v in zip(self._fields, self) if v != 0)})"

_Tensor = Union[
float,
Sequence[float],
"np.ndarray[Tuple[()], np.dtype[np.generic]]",
"np.ndarray[Tuple[int], np.dtype[np.generic]]",
]

@dataclass
class Dimensioned:
value: Union[int, float, Sequence[Union[int, float]]] = 0
dimensions: Union["FoamFileBase.DimensionSet", Sequence[Union[int, float]]] = ()
value: "FoamFileBase._Tensor" = 0
dimensions: Union["FoamFileBase.DimensionSet", Sequence[float]] = ()
name: Optional[str] = None

def __post_init__(self) -> None:
if not isinstance(self.dimensions, FoamFileBase.DimensionSet):
self.dimensions = FoamFileBase.DimensionSet(*self.dimensions)

_Field = Union[
_Tensor, Sequence[_Tensor], "np.ndarray[Tuple[int, int], np.dtype[np.generic]]"
]

Data = Union[
str,
int,
Expand All @@ -43,9 +54,8 @@ def __post_init__(self) -> None:
DimensionSet,
Sequence["Data"],
Mapping[str, "Data"],
"np.ndarray[Tuple[()], np.dtype[np.generic]]",
"np.ndarray[Tuple[int], np.dtype[np.generic]]",
"np.ndarray[Tuple[int, int], np.dtype[np.generic]]",
_Tensor,
_Field,
]
"""
A value that can be stored in an OpenFOAM file.
Expand Down
67 changes: 14 additions & 53 deletions foamlib/_files/_files.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sys
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union, cast
from typing import Any, Optional, Tuple, Union, cast

if sys.version_info >= (3, 8):
from typing import Literal
Expand All @@ -17,9 +17,6 @@
from ._serialization import Kind, dumps
from ._util import is_sequence

if TYPE_CHECKING:
import numpy as np


class FoamFile(
FoamFileBase,
Expand Down Expand Up @@ -159,7 +156,7 @@ def object_(self, value: str) -> None:

def __getitem__(
self, keywords: Optional[Union[str, Tuple[str, ...]]]
) -> Union["FoamFile.Data", "FoamFile.SubDict"]:
) -> "FoamFile.Data":
if not keywords:
keywords = ()
elif not isinstance(keywords, tuple):
Expand All @@ -169,6 +166,8 @@ def __getitem__(

value = parsed[keywords]

assert not isinstance(value, Mapping)

if value is ...:
return FoamFile.SubDict(self, keywords)
return deepcopy(value)
Expand Down Expand Up @@ -374,36 +373,17 @@ def type(self, data: str) -> None:
@property
def value(
self,
) -> Union[
int,
float,
Sequence[Union[int, float, Sequence[Union[int, float]]]],
"np.ndarray[Tuple[()], np.dtype[np.generic]]",
"np.ndarray[Tuple[int], np.dtype[np.generic]]",
"np.ndarray[Tuple[int, int], np.dtype[np.generic]]",
]:
) -> FoamFile._Field:
"""Alias of `self["value"]`."""
ret = self["value"]
if not isinstance(ret, (int, float, Sequence)):
raise TypeError("value is not a field")
return cast(
Union[
int, float, Sequence[Union[int, float, Sequence[Union[int, float]]]]
],
ret,
FoamFile._Field,
self["value"],
)

@value.setter
def value(
self,
value: Union[
int,
float,
Sequence[Union[int, float, Sequence[Union[int, float]]]],
"np.ndarray[Tuple[()], np.dtype[np.generic]]",
"np.ndarray[Tuple[int], np.dtype[np.generic]]",
"np.ndarray[Tuple[int, int], np.dtype[np.generic]]",
],
value: FoamFile._Field,
) -> None:
self["value"] = value

Expand All @@ -413,7 +393,7 @@ def value(self) -> None:

def __getitem__(
self, keywords: Optional[Union[str, Tuple[str, ...]]]
) -> Union[FoamFile.Data, FoamFile.SubDict]:
) -> FoamFile.Data:
if not keywords:
keywords = ()
elif not isinstance(keywords, tuple):
Expand All @@ -428,47 +408,28 @@ def __getitem__(
return ret

@property
def dimensions(self) -> Union[FoamFile.DimensionSet, Sequence[Union[int, float]]]:
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")
return ret

@dimensions.setter
def dimensions(
self, value: Union[FoamFile.DimensionSet, Sequence[Union[int, float]]]
) -> None:
def dimensions(self, value: Union[FoamFile.DimensionSet, Sequence[float]]) -> None:
self["dimensions"] = value

@property
def internal_field(
self,
) -> Union[
int,
float,
Sequence[Union[int, float, Sequence[Union[int, float]]]],
"np.ndarray[Tuple[()], np.dtype[np.generic]]",
"np.ndarray[Tuple[int], np.dtype[np.generic]]",
"np.ndarray[Tuple[int, int], np.dtype[np.generic]]",
]:
) -> FoamFile._Field:
"""Alias of `self["internalField"]`."""
ret = self["internalField"]
if not isinstance(ret, (int, float, Sequence)):
raise TypeError("internalField is not a field")
return cast(Union[int, float, Sequence[Union[int, float]]], ret)
return cast(FoamFile._Field, self["internalField"])

@internal_field.setter
def internal_field(
self,
value: Union[
int,
float,
Sequence[Union[int, float, Sequence[Union[int, float]]]],
"np.ndarray[Tuple[()], np.dtype[np.generic]]",
"np.ndarray[Tuple[int], np.dtype[np.generic]]",
"np.ndarray[Tuple[int, int], np.dtype[np.generic]]",
],
value: FoamFile._Field,
) -> None:
self["internalField"] = value

Expand Down
Loading