brainsets

Base Classes

StringIntEnum

Base class for string-integer enums

Dictable

Base class for dataclasses that can be converted to dictionaries

class StringIntEnum(value)[source]

Bases: Enum

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()

>>> 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
classmethod from_string(string)[source]

Convert a string to an enum member. This method is case insensitive and will replace spaces with underscores.

Parameters:

string (str) – The string to convert to an enum member.

Return type:

StringIntEnum

Examples

>>> from brainsets.taxonomy import Sex
>>> Sex.from_string("Male")
<Sex.MALE: 1>
>>> Sex.from_string("M")
<Sex.MALE: 1>
classmethod max_value()[source]

Return the maximum value in the enum class.

class Dictable[source]

Bases: object

A dataclass that can be converted to a dict.

to_dict()[source]

Convert the dataclass instance to a dictionary.

Returns:

A dictionary containing all fields of the dataclass as key-value pairs.

Return type:

dict

>>> from dataclasses import dataclass
>>> @dataclass
... class Person(Dictable):
...     name: str
...     age: int

>>> p = Person("Alice", 30)
>>> p.to_dict()
{'name': 'Alice', 'age': 30}

Serialization Functions

string_int_enum_serialize_fn(obj, serialize_fn_map=None)[source]

Convert a StringIntEnum object to a string.

datetime_serialize_fn(obj, serialize_fn_map=None)[source]

Convert a datetime object to a string.

serialize_fn_map = {<class 'datetime.datetime'>: <function datetime_serialize_fn>, <enum 'StringIntEnum'>: <function string_int_enum_serialize_fn>}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)