[docs]classStringIntEnum(Enum,metaclass=NestedEnumType):r"""Base class for string-integer enums. This class extends Python's built-in Enum class to provide: - String representation via __str__ - Integer representation via __int__ - Case-insensitive string parsing via from_string() - Maximum value lookup via max_value() .. code-block:: python >>> class Color(StringIntEnum): ... RED = 1 ... BLUE = 2 >>> str(Color.RED) 'RED' >>> int(Color.RED) 1 >>> Color.from_string("red") <Color.RED: 1> >>> Color.max_value() 2 """def__str__(self):ifself._parentisnotNone:returnf"{str(self._parent)}.{self.name}"else:returnself.namedef__int__(self):returnself.value
[docs]@classmethoddeffrom_string(cls,string:str)->"StringIntEnum":r"""Convert a string to an enum member. This method is case insensitive and will replace spaces with underscores. Args: string: The string to convert to an enum member. Examples: >>> from brainsets.taxonomy import Sex >>> Sex.from_string("Male") <Sex.MALE: 1> >>> Sex.from_string("M") <Sex.MALE: 1> """nested_string=string.split(".",maxsplit=1)iflen(nested_string)>1:parent=cls.from_string(nested_string[0])returnparent._parent_cls.from_string(nested_string[1])else:# normalize string by replacing spaces with underscores and converting# to upper casenormalized_string=string.strip().upper().replace(" ","_")# create a mapping of enum names to enum membersmapping={name.upper():memberforname,memberincls.__members__.items()}# try to match the string to an enum nameifnormalized_stringinmapping:returnmapping[normalized_string]# if there is no match raise an errorraiseValueError(f"{normalized_string} does not exist in {cls.__name__}, ""consider adding it to the enum.")
[docs]@classmethoddefmax_value(cls):r"""Return the maximum value in the enum class."""returnmax(cls.__members__.values(),key=lambdax:x.value).value
[docs]classDictable:r"""A dataclass that can be converted to a dict."""
[docs]defto_dict(self):r"""Convert the dataclass instance to a dictionary. Returns: dict: A dictionary containing all fields of the dataclass as key-value pairs. .. code-block:: python >>> from dataclasses import dataclass >>> @dataclass ... class Person(Dictable): ... name: str ... age: int >>> p = Person("Alice", 30) >>> p.to_dict() {'name': 'Alice', 'age': 30} """fromdataclassesimportasdictreturn{k:vfork,vinasdict(self).items()}# type: ignore
[docs]defstring_int_enum_serialize_fn(obj,serialize_fn_map=None):r"""Convert a StringIntEnum object to a string."""returnstr(obj)
[docs]defdatetime_serialize_fn(obj,serialize_fn_map=None):r"""Convert a datetime object to a string."""returnstr(obj)