From 1efa4b7f1f854118bbb37dd89cb9febdf01107bf Mon Sep 17 00:00:00 2001 From: Philipp Holl Date: Sun, 22 Dec 2024 16:42:27 +0100 Subject: [PATCH] Shape refactor: Fix dataclass slots for Python < 3.10 --- phiml/math/_shape.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/phiml/math/_shape.py b/phiml/math/_shape.py index daf847d5..c0393622 100644 --- a/phiml/math/_shape.py +++ b/phiml/math/_shape.py @@ -1,4 +1,5 @@ import re +import sys import warnings from dataclasses import dataclass, replace from functools import cached_property @@ -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): @@ -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] @@ -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] @@ -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]