brainhops._core.enum
Classes
EnumConverter
The converter of a free-text value that has a list of known terms.
The known terms are the members of an enum. A string that is the
value of a member becomes that member, any other string stays a
string, and None stays None. A field annotated with
ConvertTo(EnumConverter(SpaceEnum)) therefore holds a SpaceEnum
member for a known space and the plain string for any other space.
bagof does not convert a Union[Enum, str] this way by itself. Its
union converter returns a value that already fits one branch of the
union as it is, so a string stays a string, and the enum branch is
never tried. Registering a converter for the union does not help
either, because bagof matches a parametrised union by equality:
each enum, and each wrapping of its union (Optional[...], or the
metadata Maybe[...], which flatten into other unions), would need a
registration of its own, and a shape that was left out would silently
keep the string. An explicit converter on the field cannot be missed.
The converter is a class rather than a closure so that it has a
readable repr and can be pickled, since it is stored in the
metadata of a field.
Examples:
>>> from brainhops.datamodel.enums import SpaceEnum
>>> convert = EnumConverter(SpaceEnum)
>>> convert("scanner")
<SpaceEnum.scanner: 'scanner'>
>>> convert("my-template")
'my-template'
>>> convert
EnumConverter(SpaceEnum)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enum
|
type
|
The enum whose members are the known terms. |
required |
Methods:
__call__
Convert a value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
(Enum, str or None)
|
The value to convert. |
required |
Returns:
| Type | Description |
|---|---|
(Enum, str or None)
|
The member whose value is |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |