|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import sys |
| 4 | +from enum import ( |
| 5 | + EnumMeta, |
| 6 | + IntEnum, |
| 7 | +) |
| 8 | +from types import MappingProxyType |
| 9 | +from typing import ( |
| 10 | + TYPE_CHECKING, |
| 11 | + Any, |
| 12 | + Dict, |
| 13 | + Optional, |
| 14 | + Tuple, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +if TYPE_CHECKING: |
| 19 | + from collections.abc import ( |
| 20 | + Generator, |
| 21 | + Mapping, |
| 22 | + ) |
| 23 | + |
| 24 | + from typing_extensions import ( |
| 25 | + Never, |
| 26 | + Self, |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +def _is_descriptor(obj: object) -> bool: |
| 31 | + return ( |
| 32 | + hasattr(obj, "__get__") or hasattr(obj, "__set__") or hasattr(obj, "__delete__") |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +class EnumType(EnumMeta if TYPE_CHECKING else type): |
| 37 | + _value_map_: Mapping[int, Enum] |
| 38 | + _member_map_: Mapping[str, Enum] |
| 39 | + |
| 40 | + def __new__( |
| 41 | + mcs, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any] |
| 42 | + ) -> Self: |
| 43 | + value_map = {} |
| 44 | + member_map = {} |
| 45 | + |
| 46 | + new_mcs = type( |
| 47 | + f"{name}Type", |
| 48 | + tuple( |
| 49 | + dict.fromkeys( |
| 50 | + [base.__class__ for base in bases if base.__class__ is not type] |
| 51 | + + [EnumType, type] |
| 52 | + ) |
| 53 | + ), # reorder the bases so EnumType and type are last to avoid conflicts |
| 54 | + {"_value_map_": value_map, "_member_map_": member_map}, |
| 55 | + ) |
| 56 | + |
| 57 | + members = { |
| 58 | + name: value |
| 59 | + for name, value in namespace.items() |
| 60 | + if not _is_descriptor(value) and name[0] != "_" |
| 61 | + } |
| 62 | + |
| 63 | + cls = type.__new__( |
| 64 | + new_mcs, |
| 65 | + name, |
| 66 | + bases, |
| 67 | + {key: value for key, value in namespace.items() if key not in members}, |
| 68 | + ) |
| 69 | + # this allows us to disallow member access from other members as |
| 70 | + # members become proper class variables |
| 71 | + |
| 72 | + for name, value in members.items(): |
| 73 | + if _is_descriptor(value) or name[0] == "_": |
| 74 | + continue |
| 75 | + |
| 76 | + member = value_map.get(value) |
| 77 | + if member is None: |
| 78 | + member = cls.__new__(cls, name=name, value=value) # type: ignore |
| 79 | + value_map[value] = member |
| 80 | + member_map[name] = member |
| 81 | + type.__setattr__(new_mcs, name, member) |
| 82 | + |
| 83 | + return cls |
| 84 | + |
| 85 | + if not TYPE_CHECKING: |
| 86 | + |
| 87 | + def __call__(cls, value: int) -> Enum: |
| 88 | + try: |
| 89 | + return cls._value_map_[value] |
| 90 | + except (KeyError, TypeError): |
| 91 | + raise ValueError(f"{value!r} is not a valid {cls.__name__}") from None |
| 92 | + |
| 93 | + def __iter__(cls) -> Generator[Enum, None, None]: |
| 94 | + yield from cls._member_map_.values() |
| 95 | + |
| 96 | + if sys.version_info >= (3, 8): # 3.8 added __reversed__ to dict_values |
| 97 | + |
| 98 | + def __reversed__(cls) -> Generator[Enum, None, None]: |
| 99 | + yield from reversed(cls._member_map_.values()) |
| 100 | + |
| 101 | + else: |
| 102 | + |
| 103 | + def __reversed__(cls) -> Generator[Enum, None, None]: |
| 104 | + yield from reversed(tuple(cls._member_map_.values())) |
| 105 | + |
| 106 | + def __getitem__(cls, key: str) -> Enum: |
| 107 | + return cls._member_map_[key] |
| 108 | + |
| 109 | + @property |
| 110 | + def __members__(cls) -> MappingProxyType[str, Enum]: |
| 111 | + return MappingProxyType(cls._member_map_) |
| 112 | + |
| 113 | + def __repr__(cls) -> str: |
| 114 | + return f"<enum {cls.__name__!r}>" |
| 115 | + |
| 116 | + def __len__(cls) -> int: |
| 117 | + return len(cls._member_map_) |
| 118 | + |
| 119 | + def __setattr__(cls, name: str, value: Any) -> Never: |
| 120 | + raise AttributeError(f"{cls.__name__}: cannot reassign Enum members.") |
| 121 | + |
| 122 | + def __delattr__(cls, name: str) -> Never: |
| 123 | + raise AttributeError(f"{cls.__name__}: cannot delete Enum members.") |
| 124 | + |
| 125 | + def __contains__(cls, member: object) -> bool: |
| 126 | + return isinstance(member, cls) and member.name in cls._member_map_ |
| 127 | + |
| 128 | + |
| 129 | +class Enum(IntEnum if TYPE_CHECKING else int, metaclass=EnumType): |
| 130 | + """ |
| 131 | + The base class for protobuf enumerations, all generated enumerations will |
| 132 | + inherit from this. Emulates `enum.IntEnum`. |
| 133 | + """ |
| 134 | + |
| 135 | + name: Optional[str] |
| 136 | + value: int |
| 137 | + |
| 138 | + if not TYPE_CHECKING: |
| 139 | + |
| 140 | + def __new__(cls, *, name: Optional[str], value: int) -> Self: |
| 141 | + self = super().__new__(cls, value) |
| 142 | + super().__setattr__(self, "name", name) |
| 143 | + super().__setattr__(self, "value", value) |
| 144 | + return self |
| 145 | + |
| 146 | + def __str__(self) -> str: |
| 147 | + return self.name or "None" |
| 148 | + |
| 149 | + def __repr__(self) -> str: |
| 150 | + return f"{self.__class__.__name__}.{self.name}" |
| 151 | + |
| 152 | + def __setattr__(self, key: str, value: Any) -> Never: |
| 153 | + raise AttributeError( |
| 154 | + f"{self.__class__.__name__} Cannot reassign a member's attributes." |
| 155 | + ) |
| 156 | + |
| 157 | + def __delattr__(self, item: Any) -> Never: |
| 158 | + raise AttributeError( |
| 159 | + f"{self.__class__.__name__} Cannot delete a member's attributes." |
| 160 | + ) |
| 161 | + |
| 162 | + @classmethod |
| 163 | + def try_value(cls, value: int = 0) -> Self: |
| 164 | + """Return the value which corresponds to the value. |
| 165 | +
|
| 166 | + Parameters |
| 167 | + ----------- |
| 168 | + value: :class:`int` |
| 169 | + The value of the enum member to get. |
| 170 | +
|
| 171 | + Returns |
| 172 | + ------- |
| 173 | + :class:`Enum` |
| 174 | + The corresponding member or a new instance of the enum if |
| 175 | + ``value`` isn't actually a member. |
| 176 | + """ |
| 177 | + try: |
| 178 | + return cls._value_map_[value] |
| 179 | + except (KeyError, TypeError): |
| 180 | + return cls.__new__(cls, name=None, value=value) |
| 181 | + |
| 182 | + @classmethod |
| 183 | + def from_string(cls, name: str) -> Self: |
| 184 | + """Return the value which corresponds to the string name. |
| 185 | +
|
| 186 | + Parameters |
| 187 | + ----------- |
| 188 | + name: :class:`str` |
| 189 | + The name of the enum member to get. |
| 190 | +
|
| 191 | + Raises |
| 192 | + ------- |
| 193 | + :exc:`ValueError` |
| 194 | + The member was not found in the Enum. |
| 195 | + """ |
| 196 | + try: |
| 197 | + return cls._member_map_[name] |
| 198 | + except KeyError as e: |
| 199 | + raise ValueError(f"Unknown value {name} for enum {cls.__name__}") from e |
0 commit comments