-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypes.py
54 lines (43 loc) · 1.58 KB
/
types.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Custom types used in RXN projects."""
from enum import Enum
from typing import Any, Type, TypeVar
T = TypeVar("T", bound="RxnEnum")
class RxnEnum(Enum):
"""
Custom enum with additional functions for string conversion.
Has the following functionality compared to a standard Enum:
* to_string() to generate a lowercase representation of the instance.
* from_string(value) to instantiate from a string.
* Constructor is valid both with a string and with another enum instance.
"""
def to_string(self) -> str:
"""
Convert the enum to a string representation (all lowercase).
"""
return self.name.lower()
@classmethod
def from_string(cls: Type[T], value: str) -> T:
"""
Construct the enum from a string, i.e. from the the strings of its
possible values.
Args:
value: string to convert to an instance of the Enum.
Raises:
ValueError if the value is not found.
Returns:
An instance of the Enum.
"""
try:
return cls[value.upper()]
except KeyError as e:
allowed_values = [v.to_string() for v in cls]
allowed_values_str = ", ".join(allowed_values)
raise ValueError(
f'Invalid value: "{value}". Only the following are allowed: {allowed_values_str}.'
) from e
@classmethod
def _missing_(cls: Type[T], value: Any) -> T:
"""
Overriden to allow instantiation from both string and enum value.
"""
return cls.from_string(value)