From d471c265efe6e43bb43a305e7b3c327b282261c5 Mon Sep 17 00:00:00 2001 From: Mauko Quiroga Date: Fri, 20 Sep 2024 18:06:15 +0200 Subject: [PATCH] refactor(enums): fix linter warnings --- openfisca_core/indexed_enums/enum.py | 16 +++++++++++----- openfisca_core/indexed_enums/enum_array.py | 18 ++++++++++++++---- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/openfisca_core/indexed_enums/enum.py b/openfisca_core/indexed_enums/enum.py index bd388d03f..960c16b91 100644 --- a/openfisca_core/indexed_enums/enum.py +++ b/openfisca_core/indexed_enums/enum.py @@ -64,14 +64,14 @@ def encode( return array # String array - if isinstance(array, numpy.ndarray) and array.dtype.kind in {"U", "S"}: + if array.dtype.kind in {"U", "S"}: array = numpy.select( [array == item.name for item in cls], [item.index for item in cls], ).astype(numpy.int16) # Enum items arrays - elif isinstance(array, numpy.ndarray) and array.dtype.kind == "O": + elif array.dtype.kind == "O": # Ensure we are comparing the comparable. The problem this fixes: # On entering this method "cls" will generally come from # variable.possible_values, while the array values may come from @@ -84,12 +84,18 @@ def encode( # name to check that the values in the array, if non-empty, are of # the right type. if len(array) > 0 and cls.__name__ is array[0].__class__.__name__: - cls = array[0].__class__ + klass = array[0].__class__ + + else: + klass = cls array = numpy.select( - [array == item for item in cls], - [item.index for item in cls], + [array == item for item in klass], + [item.index for item in klass], ).astype(numpy.int16) array = numpy.asarray(array, dtype=numpy.int16) return EnumArray(array, cls) + + +__all__ = ["Enum"] diff --git a/openfisca_core/indexed_enums/enum_array.py b/openfisca_core/indexed_enums/enum_array.py index 407cbe5c2..d8530f8d1 100644 --- a/openfisca_core/indexed_enums/enum_array.py +++ b/openfisca_core/indexed_enums/enum_array.py @@ -149,16 +149,26 @@ def _is_an_enum(self, other: object) -> TypeGuard[t.Enum]: if self.possible_values is None: raise NotImplementedError + if other is None: + raise NotImplementedError + return ( not hasattr(other, "__name__") and other.__class__.__name__ is self.possible_values.__name__ ) def _is_an_enum_type(self, other: object) -> TypeGuard[type[t.Enum]]: + name: None | str + if self.possible_values is None: raise NotImplementedError - return ( - hasattr(other, "__name__") - and other.__name__ is self.possible_values.__name__ - ) + if other is None: + raise NotImplementedError + + name = getattr(other, "__name__", None) + + return isinstance(name, str) and name is self.possible_values.__name__ + + +__all__ = ["EnumArray"]