Coverage for / home / ubuntu / lunchbox / python / lunchbox / enum.py: 100%
30 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-26 04:02 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-26 04:02 +0000
1from typing import Any # noqa F401
3from enum import Enum, EnumMeta
4# ------------------------------------------------------------------------------
7class EnumBaseMeta(EnumMeta):
8 def __repr__(self):
9 '''
10 str: String representation.
11 '''
12 return self.__name__
15class EnumBase(Enum, metaclass=EnumBaseMeta):
16 '''
17 Base class for enums.
18 '''
19 @classmethod
20 def from_string(cls, string):
21 # type: (str) -> Any
22 '''
23 Returns enum from a given string.
25 Args:
26 string (str): String.
28 Raises:
29 ValueError: If illegal string is given.
31 Returns:
32 enum: Enum.
33 '''
34 try:
35 return getattr(cls, string.upper())
36 except AttributeError:
37 c = cls.__name__
38 options = ', '.join(cls.options())
39 msg = f'{string} is not a legal {c} string. '
40 msg += f'Legal options: {options}.'
41 raise ValueError(msg)
43 @classmethod
44 def to_dict(cls):
45 # type: () -> dict
46 '''
47 Convert enum to a dictionary.
49 Returns:
50 dict: (name, value) dictionary.
51 '''
52 return {x.name: x.value for x in cls.__members__.values()}
54 @classmethod
55 def members(cls):
56 # type: () -> list[Any]
57 '''
58 Returns list of enum members.
60 Returns:
61 list[Any]: List of enum members.
62 '''
63 return list(cls.__members__.values())
65 @classmethod
66 def options(cls):
67 # type: () -> list[Any]
68 '''
69 Returns list of enum options.
71 Returns:
72 list[Any]: List of enum options.
73 '''
74 vals = list(cls.__members__.values())
75 if isinstance(vals[0].value, list | tuple):
76 return [x.value[0] for x in vals]
77 return [x.value for x in vals]
79 def __repr__(self):
80 # type: () -> str
81 '''
82 str: String representation.
83 '''
84 return self.__str__()