Skip to content

enum

EnumManipulator

EnumManipulator(input_enum: EnumMeta)

Inspect and filter members of an Enum class.

Examples:

>>> from enum import Enum
>>> from ures.tools.enum import EnumManipulator
>>> class Color(Enum):
...     RED = 1
>>> EnumManipulator(Color).check_key("RED")
True

Initialize the EnumManipulator instance with a given Enum.

Parameters:

  • input_enum (EnumMeta) –

    An Enum class to be manipulated.

Examples:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
>>> manipulator = EnumManipulator(Color)
Source code in ures/tools/enum.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def __init__(self, input_enum: EnumMeta):
    """
    Initialize the EnumManipulator instance with a given Enum.

    Args:
        input_enum (EnumMeta): An Enum class to be manipulated.

    Examples:
        >>> from enum import Enum
        >>> class Color(Enum):
        ...     RED = 1
        ...     GREEN = 2
        >>> manipulator = EnumManipulator(Color)
    """
    self._enum = input_enum

fetch_enums property

fetch_enums: EnumMeta

Retrieve the underlying Enum class.

Returns:

  • EnumMeta ( EnumMeta ) –

    The Enum class provided during initialization.

Examples:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
>>> manipulator = EnumManipulator(Color)
>>> enums = manipulator.fetch_enums
>>> isinstance(enums, type)  # Enum classes are types
True

fetch_keys

fetch_keys() -> List[str]

Get a list of all key names (member names) from the Enum.

Returns:

  • List[str] –

    List[str]: A list of key names defined in the Enum.

Examples:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     BLUE = 3
>>> manipulator = EnumManipulator(Color)
>>> manipulator.fetch_keys()
['RED', 'BLUE']
Source code in ures/tools/enum.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def fetch_keys(self) -> List[str]:
    """
    Get a list of all key names (member names) from the Enum.

    Returns:
        List[str]: A list of key names defined in the Enum.

    Examples:
        >>> from enum import Enum
        >>> class Color(Enum):
        ...     RED = 1
        ...     BLUE = 3
        >>> manipulator = EnumManipulator(Color)
        >>> manipulator.fetch_keys()
        ['RED', 'BLUE']
    """
    return self.fetch_enums._member_names_

fetch_enum

fetch_enum(key_name: str) -> Optional[Enum]

Retrieve an Enum member by its key name (case-insensitive).

Parameters:

  • key_name (str) –

    The key name to fetch.

Returns:

  • Optional[Enum] –

    Optional[Enum]: The Enum member if found; otherwise, None.

Examples:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
>>> manipulator = EnumManipulator(Color)
>>> member = manipulator.fetch_enum("red")
>>> member.value
1
Source code in ures/tools/enum.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def fetch_enum(self, key_name: str) -> Optional[Enum]:
    """
    Retrieve an Enum member by its key name (case-insensitive).

    Args:
        key_name (str): The key name to fetch.

    Returns:
        Optional[Enum]: The Enum member if found; otherwise, None.

    Examples:
        >>> from enum import Enum
        >>> class Color(Enum):
        ...     RED = 1
        ...     GREEN = 2
        >>> manipulator = EnumManipulator(Color)
        >>> member = manipulator.fetch_enum("red")
        >>> member.value
        1
    """
    for _key in self.fetch_keys():
        if key_name.lower() == str(_key).lower():
            return self.fetch_enums[_key]
    return None

check_key

check_key(key_name: str) -> bool

Check whether a given key exists in the Enum.

Parameters:

  • key_name (str) –

    The key name to check.

Returns:

  • bool ( bool ) –

    True if the key exists; otherwise, False.

Examples:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     BLUE = 3
>>> manipulator = EnumManipulator(Color)
>>> manipulator.check_key("RED")
True
>>> manipulator.check_key("GREEN")
False
Source code in ures/tools/enum.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def check_key(self, key_name: str) -> bool:
    """
    Check whether a given key exists in the Enum.

    Args:
        key_name (str): The key name to check.

    Returns:
        bool: True if the key exists; otherwise, False.

    Examples:
        >>> from enum import Enum
        >>> class Color(Enum):
        ...     RED = 1
        ...     BLUE = 3
        >>> manipulator = EnumManipulator(Color)
        >>> manipulator.check_key("RED")
        True
        >>> manipulator.check_key("GREEN")
        False
    """
    return self.fetch_enum(key_name) is not None

fetch_value

fetch_value(key_name: str) -> Any | None

Retrieve the value associated with a given key in the Enum.

Parameters:

  • key_name (str) –

    The key name for which to fetch the value.

Returns:

  • Any | None –

    The enum member value if the key exists, otherwise None.

Examples:

>>> from enum import Enum
>>> class Status(Enum):
...     SUCCESS = "ok"
...     FAILURE = "error"
>>> manipulator = EnumManipulator(Status)
>>> manipulator.fetch_value("FAILURE")
'error'
Source code in ures/tools/enum.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def fetch_value(self, key_name: str) -> Any | None:
    """
    Retrieve the value associated with a given key in the Enum.

    Args:
        key_name (str): The key name for which to fetch the value.

    Returns:
        The enum member value if the key exists, otherwise None.

    Examples:
        >>> from enum import Enum
        >>> class Status(Enum):
        ...     SUCCESS = "ok"
        ...     FAILURE = "error"
        >>> manipulator = EnumManipulator(Status)
        >>> manipulator.fetch_value("FAILURE")
        'error'
    """
    member = self.fetch_enum(key_name)
    if member is not None:
        return member.value
    return None

filter_by

filter_by(keyword: str, field: str | None = None) -> list

Filter and return keys from the Enum where the specified keyword matches.

If no field is provided, the keyword is compared to the string representation of the Enum member's value. Otherwise, the specified attribute (field) of the member's value is used for comparison.

Parameters:

  • keyword (str) –

    The keyword to search for.

  • field (str, default: None ) –

    The attribute of the Enum member's value to search within. Defaults to None.

Returns:

  • list ( list ) –

    A list of keys for which the keyword was found.

Examples:

>>> from enum import Enum
>>> class Fruit(Enum):
...     APPLE = "red"
...     BANANA = "yellow"
...     GRAPE = "purple"
>>> manipulator = EnumManipulator(Fruit)
>>> manipulator.filter_by("red")
['APPLE']
Source code in ures/tools/enum.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def filter_by(self, keyword: str, field: str | None = None) -> list:
    """
    Filter and return keys from the Enum where the specified keyword matches.

    If no field is provided, the keyword is compared to the string representation
    of the Enum member's value. Otherwise, the specified attribute (field) of the member's
    value is used for comparison.

    Args:
        keyword (str): The keyword to search for.
        field (str, optional): The attribute of the Enum member's value to search within.
            Defaults to None.

    Returns:
        list: A list of keys for which the keyword was found.

    Examples:
        >>> from enum import Enum
        >>> class Fruit(Enum):
        ...     APPLE = "red"
        ...     BANANA = "yellow"
        ...     GRAPE = "purple"
        >>> manipulator = EnumManipulator(Fruit)
        >>> manipulator.filter_by("red")
        ['APPLE']
    """
    result = []
    for key in self.fetch_keys():
        member_value = self.fetch_enums[key].value
        if field is None:
            if keyword == str(member_value):
                result.append(key)
        else:
            # Assume the member_value has an attribute named field.
            field_value = getattr(member_value, field, None)
            if isinstance(field_value, str):
                if keyword.lower() in field_value.lower():
                    result.append(key)
            elif isinstance(field_value, list):
                if keyword.lower() in [str(item).lower() for item in field_value]:
                    result.append(key)
    return result