Skip to content

Commit

Permalink
Shape refactor: Fix dataclass slots for Python < 3.10
Browse files Browse the repository at this point in the history
  • Loading branch information
holl- committed Dec 22, 2024
1 parent df9ee02 commit 1efa4b7
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions phiml/math/_shape.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
import sys
import warnings
from dataclasses import dataclass, replace
from functools import cached_property
Expand All @@ -24,6 +25,14 @@
DEBUG_CHECKS = []


def enable_debug_checks():
"""
Once called, additional type checks are enabled.
This may result in a noticeable drop in performance.
"""
DEBUG_CHECKS.append(True)


class ShapeMeta(type(Protocol)):

def __instancecheck__(self, obj):
Expand Down Expand Up @@ -732,15 +741,13 @@ def meshgrid(self, names=False):
pass


def enable_debug_checks():
"""
Once called, additional type checks are enabled.
This may result in a noticeable drop in performance.
"""
DEBUG_CHECKS.append(True)
if sys.version_info >= (3, 10):
_dataclass_kwargs = {'slots': True}
else:
_dataclass_kwargs = {}


@dataclass(frozen=True, slots=True)
@dataclass(frozen=True, **_dataclass_kwargs)
class Dim:
name: str
size: Union[int, Any]
Expand Down Expand Up @@ -1104,7 +1111,7 @@ def as_type(self, new_type: Callable):
return Dim(_apply_prefix(self.name, dim_type), self.size, dim_type, self.slice_names)


@dataclass(frozen=True, slots=False) # slots not compatible with @cached_property
@dataclass(frozen=True, **_dataclass_kwargs) # slots not compatible with @cached_property
class PureShape:
dim_type: str
dims: Dict[str, Dim]
Expand Down Expand Up @@ -1469,7 +1476,7 @@ def as_type(self, new_type: Callable):
return {batch: self.as_batch, dual: self.as_dual, instance: self.as_instance, spatial: self.as_spatial, channel: self.as_channel}[new_type]()


@dataclass(frozen=True, slots=True)
@dataclass(frozen=True, **_dataclass_kwargs)
class MixedShape:
batch: Union[PureShape, Dim]
dual: Union[PureShape, Dim]
Expand Down

0 comments on commit 1efa4b7

Please sign in to comment.