Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1 | import sys |
Ethan Furman | e03ea37 | 2013-09-25 07:14:41 -0700 | [diff] [blame] | 2 | from types import MappingProxyType, DynamicClassAttribute |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 3 | from builtins import property as _bltin_property, bin as _bltin_bin |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 4 | |
Ethan Furman | e5754ab | 2015-09-17 22:03:52 -0700 | [diff] [blame] | 5 | |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 6 | __all__ = [ |
| 7 | 'EnumMeta', |
Ethan Furman | 0063ff4 | 2020-09-21 17:23:13 -0700 | [diff] [blame] | 8 | 'Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag', |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 9 | 'auto', 'unique', |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 10 | 'property', |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 11 | 'FlagBoundary', 'STRICT', 'CONFORM', 'EJECT', 'KEEP', |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 12 | ] |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 13 | |
| 14 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 15 | # Dummy value for Enum and Flag as there are explicit checks for them |
| 16 | # before they have been created. |
| 17 | # This is also why there are checks in EnumMeta like `if Enum is not None` |
| 18 | Enum = Flag = EJECT = None |
| 19 | |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 20 | def _is_descriptor(obj): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 21 | """ |
| 22 | Returns True if obj is a descriptor, False otherwise. |
| 23 | """ |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 24 | return ( |
| 25 | hasattr(obj, '__get__') or |
| 26 | hasattr(obj, '__set__') or |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 27 | hasattr(obj, '__delete__') |
| 28 | ) |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 29 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 30 | def _is_dunder(name): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 31 | """ |
| 32 | Returns True if a __dunder__ name, False otherwise. |
| 33 | """ |
| 34 | return ( |
| 35 | len(name) > 4 and |
Brennan D Baraban | 8b914d2 | 2019-03-03 14:09:11 -0800 | [diff] [blame] | 36 | name[:2] == name[-2:] == '__' and |
| 37 | name[2] != '_' and |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 38 | name[-3] != '_' |
| 39 | ) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 40 | |
| 41 | def _is_sunder(name): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 42 | """ |
| 43 | Returns True if a _sunder_ name, False otherwise. |
| 44 | """ |
| 45 | return ( |
| 46 | len(name) > 2 and |
Brennan D Baraban | 8b914d2 | 2019-03-03 14:09:11 -0800 | [diff] [blame] | 47 | name[0] == name[-1] == '_' and |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 48 | name[1:2] != '_' and |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 49 | name[-2:-1] != '_' |
| 50 | ) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 51 | |
Ethan Furman | 7cf0aad | 2020-12-09 17:12:11 -0800 | [diff] [blame] | 52 | def _is_private(cls_name, name): |
| 53 | # do not use `re` as `re` imports `enum` |
| 54 | pattern = '_%s__' % (cls_name, ) |
| 55 | if ( |
| 56 | len(name) >= 5 |
| 57 | and name.startswith(pattern) |
| 58 | and name[len(pattern)] != '_' |
| 59 | and (name[-1] != '_' or name[-2] != '_') |
| 60 | ): |
| 61 | return True |
| 62 | else: |
| 63 | return False |
| 64 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 65 | def _is_single_bit(num): |
| 66 | """ |
| 67 | True if only one bit set in num (should be an int) |
| 68 | """ |
| 69 | if num == 0: |
| 70 | return False |
| 71 | num &= num - 1 |
| 72 | return num == 0 |
| 73 | |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 74 | def _make_class_unpicklable(obj): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 75 | """ |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 76 | Make the given obj un-picklable. |
| 77 | |
| 78 | obj should be either a dictionary, on an Enum |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 79 | """ |
Ethan Furman | ca1b794 | 2014-02-08 11:36:27 -0800 | [diff] [blame] | 80 | def _break_on_call_reduce(self, proto): |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 81 | raise TypeError('%r cannot be pickled' % self) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 82 | if isinstance(obj, dict): |
| 83 | obj['__reduce_ex__'] = _break_on_call_reduce |
| 84 | obj['__module__'] = '<unknown>' |
| 85 | else: |
| 86 | setattr(obj, '__reduce_ex__', _break_on_call_reduce) |
| 87 | setattr(obj, '__module__', '<unknown>') |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 88 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 89 | def _iter_bits_lsb(num): |
| 90 | while num: |
| 91 | b = num & (~num + 1) |
| 92 | yield b |
| 93 | num ^= b |
| 94 | |
| 95 | def bin(num, max_bits=None): |
| 96 | """ |
| 97 | Like built-in bin(), except negative values are represented in |
| 98 | twos-compliment, and the leading bit always indicates sign |
| 99 | (0=positive, 1=negative). |
| 100 | |
| 101 | >>> bin(10) |
| 102 | '0b0 1010' |
| 103 | >>> bin(~10) # ~10 is -11 |
| 104 | '0b1 0101' |
| 105 | """ |
| 106 | |
| 107 | ceiling = 2 ** (num).bit_length() |
| 108 | if num >= 0: |
| 109 | s = _bltin_bin(num + ceiling).replace('1', '0', 1) |
| 110 | else: |
| 111 | s = _bltin_bin(~num ^ (ceiling - 1) + ceiling) |
| 112 | sign = s[:3] |
| 113 | digits = s[3:] |
| 114 | if max_bits is not None: |
| 115 | if len(digits) < max_bits: |
| 116 | digits = (sign[-1] * max_bits + digits)[-max_bits:] |
| 117 | return "%s %s" % (sign, digits) |
| 118 | |
| 119 | |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 120 | _auto_null = object() |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 121 | class auto: |
| 122 | """ |
| 123 | Instances are replaced with an appropriate value in Enum class suites. |
| 124 | """ |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 125 | value = _auto_null |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 126 | |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 127 | class property(DynamicClassAttribute): |
| 128 | """ |
| 129 | This is a descriptor, used to define attributes that act differently |
| 130 | when accessed through an enum member and through an enum class. |
| 131 | Instance access is the same as property(), but access to an attribute |
| 132 | through the enum class will instead look in the class' _member_map_ for |
| 133 | a corresponding enum member. |
| 134 | """ |
| 135 | |
| 136 | def __get__(self, instance, ownerclass=None): |
| 137 | if instance is None: |
| 138 | try: |
| 139 | return ownerclass._member_map_[self.name] |
| 140 | except KeyError: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 141 | raise AttributeError( |
Ethan Furman | d65b903 | 2021-02-08 17:32:38 -0800 | [diff] [blame^] | 142 | '%s: no class attribute %r' % (ownerclass.__name__, self.name) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 143 | ) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 144 | else: |
| 145 | if self.fget is None: |
Ethan Furman | d65b903 | 2021-02-08 17:32:38 -0800 | [diff] [blame^] | 146 | # check for member |
| 147 | if self.name in ownerclass._member_map_: |
| 148 | import warnings |
| 149 | warnings.warn( |
| 150 | "accessing one member from another is not supported, " |
| 151 | " and will be disabled in 3.11", |
| 152 | DeprecationWarning, |
| 153 | stacklevel=2, |
| 154 | ) |
| 155 | return ownerclass._member_map_[self.name] |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 156 | raise AttributeError( |
Ethan Furman | d65b903 | 2021-02-08 17:32:38 -0800 | [diff] [blame^] | 157 | '%s: no instance attribute %r' % (ownerclass.__name__, self.name) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 158 | ) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 159 | else: |
| 160 | return self.fget(instance) |
| 161 | |
| 162 | def __set__(self, instance, value): |
| 163 | if self.fset is None: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 164 | raise AttributeError( |
Ethan Furman | d65b903 | 2021-02-08 17:32:38 -0800 | [diff] [blame^] | 165 | "%s: cannot set instance attribute %r" % (self.clsname, self.name) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 166 | ) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 167 | else: |
| 168 | return self.fset(instance, value) |
| 169 | |
| 170 | def __delete__(self, instance): |
| 171 | if self.fdel is None: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 172 | raise AttributeError( |
Ethan Furman | d65b903 | 2021-02-08 17:32:38 -0800 | [diff] [blame^] | 173 | "%s: cannot delete instance attribute %r" % (self.clsname, self.name) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 174 | ) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 175 | else: |
| 176 | return self.fdel(instance) |
| 177 | |
| 178 | def __set_name__(self, ownerclass, name): |
| 179 | self.name = name |
| 180 | self.clsname = ownerclass.__name__ |
| 181 | |
| 182 | |
| 183 | class _proto_member: |
| 184 | """ |
| 185 | intermediate step for enum members between class execution and final creation |
| 186 | """ |
| 187 | |
| 188 | def __init__(self, value): |
| 189 | self.value = value |
| 190 | |
| 191 | def __set_name__(self, enum_class, member_name): |
| 192 | """ |
| 193 | convert each quasi-member into an instance of the new enum class |
| 194 | """ |
| 195 | # first step: remove ourself from enum_class |
| 196 | delattr(enum_class, member_name) |
| 197 | # second step: create member based on enum_class |
| 198 | value = self.value |
| 199 | if not isinstance(value, tuple): |
| 200 | args = (value, ) |
| 201 | else: |
| 202 | args = value |
| 203 | if enum_class._member_type_ is tuple: # special case for tuple enums |
| 204 | args = (args, ) # wrap it one more time |
| 205 | if not enum_class._use_args_: |
| 206 | enum_member = enum_class._new_member_(enum_class) |
| 207 | if not hasattr(enum_member, '_value_'): |
| 208 | enum_member._value_ = value |
| 209 | else: |
| 210 | enum_member = enum_class._new_member_(enum_class, *args) |
| 211 | if not hasattr(enum_member, '_value_'): |
| 212 | if enum_class._member_type_ is object: |
| 213 | enum_member._value_ = value |
| 214 | else: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 215 | try: |
| 216 | enum_member._value_ = enum_class._member_type_(*args) |
| 217 | except Exception as exc: |
| 218 | raise TypeError( |
| 219 | '_value_ not set in __new__, unable to create it' |
| 220 | ) from None |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 221 | value = enum_member._value_ |
| 222 | enum_member._name_ = member_name |
| 223 | enum_member.__objclass__ = enum_class |
| 224 | enum_member.__init__(*args) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 225 | enum_member._sort_order_ = len(enum_class._member_names_) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 226 | # If another member with the same value was already defined, the |
| 227 | # new member becomes an alias to the existing one. |
| 228 | for name, canonical_member in enum_class._member_map_.items(): |
| 229 | if canonical_member._value_ == enum_member._value_: |
| 230 | enum_member = canonical_member |
| 231 | break |
| 232 | else: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 233 | # this could still be an alias if the value is multi-bit and the |
| 234 | # class is a flag class |
| 235 | if ( |
| 236 | Flag is None |
| 237 | or not issubclass(enum_class, Flag) |
| 238 | ): |
| 239 | # no other instances found, record this member in _member_names_ |
| 240 | enum_class._member_names_.append(member_name) |
| 241 | elif ( |
| 242 | Flag is not None |
| 243 | and issubclass(enum_class, Flag) |
| 244 | and _is_single_bit(value) |
| 245 | ): |
| 246 | # no other instances found, record this member in _member_names_ |
| 247 | enum_class._member_names_.append(member_name) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 248 | # get redirect in place before adding to _member_map_ |
| 249 | # but check for other instances in parent classes first |
| 250 | need_override = False |
| 251 | descriptor = None |
| 252 | for base in enum_class.__mro__[1:]: |
| 253 | descriptor = base.__dict__.get(member_name) |
| 254 | if descriptor is not None: |
| 255 | if isinstance(descriptor, (property, DynamicClassAttribute)): |
| 256 | break |
| 257 | else: |
| 258 | need_override = True |
| 259 | # keep looking for an enum.property |
| 260 | if descriptor and not need_override: |
| 261 | # previous enum.property found, no further action needed |
| 262 | pass |
| 263 | else: |
| 264 | redirect = property() |
| 265 | redirect.__set_name__(enum_class, member_name) |
| 266 | if descriptor and need_override: |
| 267 | # previous enum.property found, but some other inherited attribute |
| 268 | # is in the way; copy fget, fset, fdel to this one |
| 269 | redirect.fget = descriptor.fget |
| 270 | redirect.fset = descriptor.fset |
| 271 | redirect.fdel = descriptor.fdel |
| 272 | setattr(enum_class, member_name, redirect) |
| 273 | # now add to _member_map_ (even aliases) |
| 274 | enum_class._member_map_[member_name] = enum_member |
| 275 | try: |
| 276 | # This may fail if value is not hashable. We can't add the value |
| 277 | # to the map, and by-value lookups for this value will be |
| 278 | # linear. |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 279 | enum_class._value2member_map_.setdefault(value, enum_member) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 280 | except TypeError: |
| 281 | pass |
| 282 | |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 283 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 284 | class _EnumDict(dict): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 285 | """ |
| 286 | Track enum member order and ensure member names are not reused. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 287 | |
| 288 | EnumMeta will use the names found in self._member_names as the |
| 289 | enumeration member names. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 290 | """ |
| 291 | def __init__(self): |
| 292 | super().__init__() |
| 293 | self._member_names = [] |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 294 | self._last_values = [] |
Ethan Furman | a4b1bb4 | 2018-01-22 07:56:37 -0800 | [diff] [blame] | 295 | self._ignore = [] |
Ethan Onstott | d9a43e2 | 2020-04-28 13:20:55 -0400 | [diff] [blame] | 296 | self._auto_called = False |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 297 | |
| 298 | def __setitem__(self, key, value): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 299 | """ |
| 300 | Changes anything not dundered or not a descriptor. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 301 | |
| 302 | If an enum member name is used twice, an error is raised; duplicate |
| 303 | values are not checked for. |
| 304 | |
| 305 | Single underscore (sunder) names are reserved. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 306 | """ |
Ethan Furman | 7cf0aad | 2020-12-09 17:12:11 -0800 | [diff] [blame] | 307 | if _is_private(self._cls_name, key): |
| 308 | # do nothing, name will be a normal attribute |
| 309 | pass |
| 310 | elif _is_sunder(key): |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 311 | if key not in ( |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 312 | '_order_', '_create_pseudo_member_', |
Ethan Furman | a4b1bb4 | 2018-01-22 07:56:37 -0800 | [diff] [blame] | 313 | '_generate_next_value_', '_missing_', '_ignore_', |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 314 | '_iter_member_', '_iter_member_by_value_', '_iter_member_by_def_', |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 315 | ): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 316 | raise ValueError( |
| 317 | '_sunder_ names, such as %r, are reserved for future Enum use' |
| 318 | % (key, ) |
| 319 | ) |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 320 | if key == '_generate_next_value_': |
Ethan Onstott | d9a43e2 | 2020-04-28 13:20:55 -0400 | [diff] [blame] | 321 | # check if members already defined as auto() |
| 322 | if self._auto_called: |
| 323 | raise TypeError("_generate_next_value_ must be defined before members") |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 324 | setattr(self, '_generate_next_value', value) |
Ethan Furman | a4b1bb4 | 2018-01-22 07:56:37 -0800 | [diff] [blame] | 325 | elif key == '_ignore_': |
| 326 | if isinstance(value, str): |
| 327 | value = value.replace(',',' ').split() |
| 328 | else: |
| 329 | value = list(value) |
| 330 | self._ignore = value |
| 331 | already = set(value) & set(self._member_names) |
| 332 | if already: |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 333 | raise ValueError( |
| 334 | '_ignore_ cannot specify already set names: %r' |
| 335 | % (already, ) |
| 336 | ) |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 337 | elif _is_dunder(key): |
Ethan Furman | e8e6127 | 2016-08-20 07:19:31 -0700 | [diff] [blame] | 338 | if key == '__order__': |
| 339 | key = '_order_' |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 340 | elif key in self._member_names: |
| 341 | # descriptor overwriting an enum? |
Ethan Furman | a658287 | 2020-12-10 13:07:00 -0800 | [diff] [blame] | 342 | raise TypeError('%r already defined as: %r' % (key, self[key])) |
Ethan Furman | a4b1bb4 | 2018-01-22 07:56:37 -0800 | [diff] [blame] | 343 | elif key in self._ignore: |
| 344 | pass |
Ethan Furman | 101e074 | 2013-09-15 12:34:36 -0700 | [diff] [blame] | 345 | elif not _is_descriptor(value): |
| 346 | if key in self: |
| 347 | # enum overwriting a descriptor? |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 348 | raise TypeError('%r already defined as: %r' % (key, self[key])) |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 349 | if isinstance(value, auto): |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 350 | if value.value == _auto_null: |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 351 | value.value = self._generate_next_value( |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 352 | key, 1, len(self._member_names), self._last_values[:], |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 353 | ) |
Ethan Furman | fc23a94 | 2020-09-16 12:37:54 -0700 | [diff] [blame] | 354 | self._auto_called = True |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 355 | value = value.value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 356 | self._member_names.append(key) |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 357 | self._last_values.append(value) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 358 | super().__setitem__(key, value) |
| 359 | |
Ethan Furman | a658287 | 2020-12-10 13:07:00 -0800 | [diff] [blame] | 360 | def update(self, members, **more_members): |
| 361 | try: |
| 362 | for name in members.keys(): |
| 363 | self[name] = members[name] |
| 364 | except AttributeError: |
| 365 | for name, value in members: |
| 366 | self[name] = value |
| 367 | for name, value in more_members.items(): |
| 368 | self[name] = value |
| 369 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 370 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 371 | class EnumMeta(type): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 372 | """ |
| 373 | Metaclass for Enum |
| 374 | """ |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 375 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 376 | @classmethod |
Ethan Furman | 6ec0ade | 2020-12-24 10:05:02 -0800 | [diff] [blame] | 377 | def __prepare__(metacls, cls, bases, **kwds): |
Ethan Furman | 3064dbf | 2020-09-16 07:11:57 -0700 | [diff] [blame] | 378 | # check that previous enum members do not exist |
| 379 | metacls._check_for_existing_members(cls, bases) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 380 | # create the namespace dict |
| 381 | enum_dict = _EnumDict() |
Ethan Furman | 7cf0aad | 2020-12-09 17:12:11 -0800 | [diff] [blame] | 382 | enum_dict._cls_name = cls |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 383 | # inherit previous flags and _generate_next_value_ function |
Ethan Furman | 3064dbf | 2020-09-16 07:11:57 -0700 | [diff] [blame] | 384 | member_type, first_enum = metacls._get_mixins_(cls, bases) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 385 | if first_enum is not None: |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 386 | enum_dict['_generate_next_value_'] = getattr( |
| 387 | first_enum, '_generate_next_value_', None, |
| 388 | ) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 389 | return enum_dict |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 390 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 391 | def __new__(metacls, cls, bases, classdict, boundary=None, **kwds): |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 392 | # an Enum class is final once enumeration items have been defined; it |
| 393 | # cannot be mixed with other types (int, float, etc.) if it has an |
| 394 | # inherited __new__ unless a new __new__ is defined (or the resulting |
| 395 | # class will fail). |
Ethan Furman | a4b1bb4 | 2018-01-22 07:56:37 -0800 | [diff] [blame] | 396 | # |
| 397 | # remove any keys listed in _ignore_ |
| 398 | classdict.setdefault('_ignore_', []).append('_ignore_') |
| 399 | ignore = classdict['_ignore_'] |
| 400 | for key in ignore: |
| 401 | classdict.pop(key, None) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 402 | # |
| 403 | # grab member names |
| 404 | member_names = classdict._member_names |
| 405 | # |
| 406 | # check for illegal enum names (any others?) |
| 407 | invalid_names = set(member_names) & {'mro', ''} |
| 408 | if invalid_names: |
| 409 | raise ValueError('Invalid enum member name: {0}'.format( |
| 410 | ','.join(invalid_names))) |
| 411 | # |
| 412 | # adjust the sunders |
| 413 | _order_ = classdict.pop('_order_', None) |
| 414 | # convert to normal dict |
| 415 | classdict = dict(classdict.items()) |
| 416 | # |
| 417 | # data type of member and the controlling Enum class |
Ethan Furman | 3064dbf | 2020-09-16 07:11:57 -0700 | [diff] [blame] | 418 | member_type, first_enum = metacls._get_mixins_(cls, bases) |
Ethan Furman | c266736 | 2020-12-07 00:17:31 -0800 | [diff] [blame] | 419 | __new__, save_new, use_args = metacls._find_new_( |
| 420 | classdict, member_type, first_enum, |
| 421 | ) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 422 | classdict['_new_member_'] = __new__ |
| 423 | classdict['_use_args_'] = use_args |
| 424 | # |
| 425 | # convert future enum members into temporary _proto_members |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 426 | # and record integer values in case this will be a Flag |
| 427 | flag_mask = 0 |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 428 | for name in member_names: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 429 | value = classdict[name] |
| 430 | if isinstance(value, int): |
| 431 | flag_mask |= value |
| 432 | classdict[name] = _proto_member(value) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 433 | # |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 434 | # house-keeping structures |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 435 | classdict['_member_names_'] = [] |
| 436 | classdict['_member_map_'] = {} |
| 437 | classdict['_value2member_map_'] = {} |
| 438 | classdict['_member_type_'] = member_type |
| 439 | # |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 440 | # Flag structures (will be removed if final class is not a Flag |
| 441 | classdict['_boundary_'] = ( |
| 442 | boundary |
| 443 | or getattr(first_enum, '_boundary_', None) |
| 444 | ) |
| 445 | classdict['_flag_mask_'] = flag_mask |
| 446 | classdict['_all_bits_'] = 2 ** ((flag_mask).bit_length()) - 1 |
| 447 | classdict['_inverted_'] = None |
| 448 | # |
Ethan Furman | 2da9504 | 2014-03-03 12:42:52 -0800 | [diff] [blame] | 449 | # If a custom type is mixed into the Enum, and it does not know how |
| 450 | # to pickle itself, pickle.dumps will succeed but pickle.loads will |
| 451 | # fail. Rather than have the error show up later and possibly far |
| 452 | # from the source, sabotage the pickle protocol for this class so |
| 453 | # that pickle.dumps also fails. |
| 454 | # |
| 455 | # However, if the new class implements its own __reduce_ex__, do not |
| 456 | # sabotage -- it's on them to make sure it works correctly. We use |
| 457 | # __reduce_ex__ instead of any of the others as it is preferred by |
| 458 | # pickle over __reduce__, and it handles all pickle protocols. |
| 459 | if '__reduce_ex__' not in classdict: |
Ethan Furman | dc87052 | 2014-02-18 12:37:12 -0800 | [diff] [blame] | 460 | if member_type is not object: |
| 461 | methods = ('__getnewargs_ex__', '__getnewargs__', |
| 462 | '__reduce_ex__', '__reduce__') |
Ethan Furman | 2da9504 | 2014-03-03 12:42:52 -0800 | [diff] [blame] | 463 | if not any(m in member_type.__dict__ for m in methods): |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 464 | _make_class_unpicklable(classdict) |
| 465 | # |
| 466 | # create a default docstring if one has not been provided |
| 467 | if '__doc__' not in classdict: |
| 468 | classdict['__doc__'] = 'An enumeration.' |
| 469 | try: |
| 470 | exc = None |
| 471 | enum_class = super().__new__(metacls, cls, bases, classdict, **kwds) |
| 472 | except RuntimeError as e: |
| 473 | # any exceptions raised by member.__new__ will get converted to a |
| 474 | # RuntimeError, so get that original exception back and raise it instead |
| 475 | exc = e.__cause__ or e |
| 476 | if exc is not None: |
| 477 | raise exc |
| 478 | # |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 479 | # double check that repr and friends are not the mixin's or various |
| 480 | # things break (such as pickle) |
Ethan Furman | 22415ad | 2020-09-15 16:28:25 -0700 | [diff] [blame] | 481 | # however, if the method is defined in the Enum itself, don't replace |
| 482 | # it |
Ethan Furman | dc87052 | 2014-02-18 12:37:12 -0800 | [diff] [blame] | 483 | for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): |
Ethan Furman | 22415ad | 2020-09-15 16:28:25 -0700 | [diff] [blame] | 484 | if name in classdict: |
| 485 | continue |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 486 | class_method = getattr(enum_class, name) |
| 487 | obj_method = getattr(member_type, name, None) |
| 488 | enum_method = getattr(first_enum, name, None) |
| 489 | if obj_method is not None and obj_method is class_method: |
| 490 | setattr(enum_class, name, enum_method) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 491 | # |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 492 | # replace any other __new__ with our own (as long as Enum is not None, |
| 493 | # anyway) -- again, this is to support pickle |
| 494 | if Enum is not None: |
| 495 | # if the user defined their own __new__, save it before it gets |
| 496 | # clobbered in case they subclass later |
| 497 | if save_new: |
| 498 | enum_class.__new_member__ = __new__ |
| 499 | enum_class.__new__ = Enum.__new__ |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 500 | # |
Ethan Furman | e8e6127 | 2016-08-20 07:19:31 -0700 | [diff] [blame] | 501 | # py3 support for definition order (helps keep py2/py3 code in sync) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 502 | # |
| 503 | # _order_ checking is spread out into three/four steps |
| 504 | # - if enum_class is a Flag: |
| 505 | # - remove any non-single-bit flags from _order_ |
| 506 | # - remove any aliases from _order_ |
| 507 | # - check that _order_ and _member_names_ match |
| 508 | # |
| 509 | # step 1: ensure we have a list |
Ethan Furman | e8e6127 | 2016-08-20 07:19:31 -0700 | [diff] [blame] | 510 | if _order_ is not None: |
| 511 | if isinstance(_order_, str): |
| 512 | _order_ = _order_.replace(',', ' ').split() |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 513 | # |
| 514 | # remove Flag structures if final class is not a Flag |
| 515 | if ( |
| 516 | Flag is None and cls != 'Flag' |
| 517 | or Flag is not None and not issubclass(enum_class, Flag) |
| 518 | ): |
| 519 | delattr(enum_class, '_boundary_') |
| 520 | delattr(enum_class, '_flag_mask_') |
| 521 | delattr(enum_class, '_all_bits_') |
| 522 | delattr(enum_class, '_inverted_') |
| 523 | elif Flag is not None and issubclass(enum_class, Flag): |
| 524 | # ensure _all_bits_ is correct and there are no missing flags |
| 525 | single_bit_total = 0 |
| 526 | multi_bit_total = 0 |
| 527 | for flag in enum_class._member_map_.values(): |
| 528 | flag_value = flag._value_ |
| 529 | if _is_single_bit(flag_value): |
| 530 | single_bit_total |= flag_value |
| 531 | else: |
| 532 | # multi-bit flags are considered aliases |
| 533 | multi_bit_total |= flag_value |
| 534 | if enum_class._boundary_ is not KEEP: |
| 535 | missed = list(_iter_bits_lsb(multi_bit_total & ~single_bit_total)) |
| 536 | if missed: |
| 537 | raise TypeError( |
| 538 | 'invalid Flag %r -- missing values: %s' |
| 539 | % (cls, ', '.join((str(i) for i in missed))) |
| 540 | ) |
| 541 | enum_class._flag_mask_ = single_bit_total |
| 542 | # |
| 543 | # set correct __iter__ |
| 544 | member_list = [m._value_ for m in enum_class] |
| 545 | if member_list != sorted(member_list): |
| 546 | enum_class._iter_member_ = enum_class._iter_member_by_def_ |
| 547 | if _order_: |
| 548 | # _order_ step 2: remove any items from _order_ that are not single-bit |
| 549 | _order_ = [ |
| 550 | o |
| 551 | for o in _order_ |
| 552 | if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_) |
| 553 | ] |
| 554 | # |
| 555 | if _order_: |
| 556 | # _order_ step 3: remove aliases from _order_ |
| 557 | _order_ = [ |
| 558 | o |
| 559 | for o in _order_ |
| 560 | if ( |
| 561 | o not in enum_class._member_map_ |
| 562 | or |
| 563 | (o in enum_class._member_map_ and o in enum_class._member_names_) |
| 564 | )] |
| 565 | # _order_ step 4: verify that _order_ and _member_names_ match |
Ethan Furman | e8e6127 | 2016-08-20 07:19:31 -0700 | [diff] [blame] | 566 | if _order_ != enum_class._member_names_: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 567 | raise TypeError( |
| 568 | 'member order does not match _order_:\n%r\n%r' |
| 569 | % (enum_class._member_names_, _order_) |
| 570 | ) |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 571 | # |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 572 | return enum_class |
| 573 | |
Ethan Furman | 5de67b1 | 2016-04-13 23:52:09 -0700 | [diff] [blame] | 574 | def __bool__(self): |
| 575 | """ |
| 576 | classes/types should always be True. |
| 577 | """ |
| 578 | return True |
| 579 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 580 | def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 581 | """ |
| 582 | Either returns an existing member, or creates a new enum class. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 583 | |
| 584 | This method is used both when an enum class is given a value to match |
| 585 | to an enumeration member (i.e. Color(3)) and for the functional API |
Ethan Furman | 23bb6f4 | 2016-11-21 09:22:05 -0800 | [diff] [blame] | 586 | (i.e. Color = Enum('Color', names='RED GREEN BLUE')). |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 587 | |
Ethan Furman | 2da9504 | 2014-03-03 12:42:52 -0800 | [diff] [blame] | 588 | When used for the functional API: |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 589 | |
Ethan Furman | 2da9504 | 2014-03-03 12:42:52 -0800 | [diff] [blame] | 590 | `value` will be the name of the new class. |
| 591 | |
| 592 | `names` should be either a string of white-space/comma delimited names |
Ethan Furman | d9925a1 | 2014-09-16 20:35:55 -0700 | [diff] [blame] | 593 | (values will start at `start`), or an iterator/mapping of name, value pairs. |
Ethan Furman | 2da9504 | 2014-03-03 12:42:52 -0800 | [diff] [blame] | 594 | |
| 595 | `module` should be set to the module this class is being created in; |
| 596 | if it is not set, an attempt to find that module will be made, but if |
| 597 | it fails the class will not be picklable. |
| 598 | |
| 599 | `qualname` should be set to the actual location this class can be found |
| 600 | at in its module; by default it is set to the global scope. If this is |
| 601 | not correct, unpickling will fail in some circumstances. |
| 602 | |
| 603 | `type`, if set, will be mixed in as the first base class. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 604 | """ |
| 605 | if names is None: # simple value lookup |
| 606 | return cls.__new__(cls, value) |
| 607 | # otherwise, functional API: we're creating a new Enum type |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 608 | return cls._create_( |
| 609 | value, |
| 610 | names, |
| 611 | module=module, |
| 612 | qualname=qualname, |
| 613 | type=type, |
| 614 | start=start, |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 615 | boundary=boundary, |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 616 | ) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 617 | |
| 618 | def __contains__(cls, member): |
Rahul Jha | 9430652 | 2018-09-10 23:51:04 +0530 | [diff] [blame] | 619 | if not isinstance(member, Enum): |
| 620 | raise TypeError( |
| 621 | "unsupported operand type(s) for 'in': '%s' and '%s'" % ( |
| 622 | type(member).__qualname__, cls.__class__.__qualname__)) |
Ethan Furman | 0081f23 | 2014-09-16 17:31:23 -0700 | [diff] [blame] | 623 | return isinstance(member, cls) and member._name_ in cls._member_map_ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 624 | |
Ethan Furman | 64a9972 | 2013-09-22 16:18:19 -0700 | [diff] [blame] | 625 | def __delattr__(cls, attr): |
| 626 | # nicer error message when someone tries to delete an attribute |
| 627 | # (see issue19025). |
| 628 | if attr in cls._member_map_: |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 629 | raise AttributeError("%s: cannot delete Enum member %r." % (cls.__name__, attr)) |
Ethan Furman | 64a9972 | 2013-09-22 16:18:19 -0700 | [diff] [blame] | 630 | super().__delattr__(attr) |
| 631 | |
Ethan Furman | 388a392 | 2013-08-12 06:51:41 -0700 | [diff] [blame] | 632 | def __dir__(self): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 633 | return ( |
| 634 | ['__class__', '__doc__', '__members__', '__module__'] |
| 635 | + self._member_names_ |
| 636 | ) |
Ethan Furman | 388a392 | 2013-08-12 06:51:41 -0700 | [diff] [blame] | 637 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 638 | def __getattr__(cls, name): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 639 | """ |
| 640 | Return the enum member matching `name` |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 641 | |
| 642 | We use __getattr__ instead of descriptors or inserting into the enum |
| 643 | class' __dict__ in order to support `name` and `value` being both |
| 644 | properties for enum members (which live in the class' __dict__) and |
| 645 | enum members themselves. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 646 | """ |
| 647 | if _is_dunder(name): |
| 648 | raise AttributeError(name) |
| 649 | try: |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 650 | return cls._member_map_[name] |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 651 | except KeyError: |
| 652 | raise AttributeError(name) from None |
| 653 | |
| 654 | def __getitem__(cls, name): |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 655 | return cls._member_map_[name] |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 656 | |
| 657 | def __iter__(cls): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 658 | """ |
| 659 | Returns members in definition order. |
| 660 | """ |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 661 | return (cls._member_map_[name] for name in cls._member_names_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 662 | |
| 663 | def __len__(cls): |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 664 | return len(cls._member_names_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 665 | |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 666 | @_bltin_property |
Ethan Furman | 2131a4a | 2013-09-14 18:11:24 -0700 | [diff] [blame] | 667 | def __members__(cls): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 668 | """ |
| 669 | Returns a mapping of member name->value. |
Ethan Furman | 2131a4a | 2013-09-14 18:11:24 -0700 | [diff] [blame] | 670 | |
| 671 | This mapping lists all enum members, including aliases. Note that this |
| 672 | is a read-only view of the internal mapping. |
Ethan Furman | 2131a4a | 2013-09-14 18:11:24 -0700 | [diff] [blame] | 673 | """ |
| 674 | return MappingProxyType(cls._member_map_) |
| 675 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 676 | def __repr__(cls): |
| 677 | return "<enum %r>" % cls.__name__ |
| 678 | |
Ethan Furman | 2131a4a | 2013-09-14 18:11:24 -0700 | [diff] [blame] | 679 | def __reversed__(cls): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 680 | """ |
| 681 | Returns members in reverse definition order. |
| 682 | """ |
Ethan Furman | 2131a4a | 2013-09-14 18:11:24 -0700 | [diff] [blame] | 683 | return (cls._member_map_[name] for name in reversed(cls._member_names_)) |
| 684 | |
Ethan Furman | f203f2d | 2013-09-06 07:16:48 -0700 | [diff] [blame] | 685 | def __setattr__(cls, name, value): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 686 | """ |
| 687 | Block attempts to reassign Enum members. |
Ethan Furman | f203f2d | 2013-09-06 07:16:48 -0700 | [diff] [blame] | 688 | |
| 689 | A simple assignment to the class namespace only changes one of the |
| 690 | several possible ways to get an Enum member from the Enum class, |
| 691 | resulting in an inconsistent Enumeration. |
Ethan Furman | f203f2d | 2013-09-06 07:16:48 -0700 | [diff] [blame] | 692 | """ |
| 693 | member_map = cls.__dict__.get('_member_map_', {}) |
| 694 | if name in member_map: |
| 695 | raise AttributeError('Cannot reassign members.') |
| 696 | super().__setattr__(name, value) |
| 697 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 698 | def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1, boundary=None): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 699 | """ |
| 700 | Convenience method to create a new Enum class. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 701 | |
| 702 | `names` can be: |
| 703 | |
| 704 | * A string containing member names, separated either with spaces or |
Ethan Furman | d9925a1 | 2014-09-16 20:35:55 -0700 | [diff] [blame] | 705 | commas. Values are incremented by 1 from `start`. |
| 706 | * An iterable of member names. Values are incremented by 1 from `start`. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 707 | * An iterable of (member name, value) pairs. |
Ethan Furman | d9925a1 | 2014-09-16 20:35:55 -0700 | [diff] [blame] | 708 | * A mapping of member name -> value pairs. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 709 | """ |
| 710 | metacls = cls.__class__ |
| 711 | bases = (cls, ) if type is None else (type, cls) |
Ethan Furman | 3064dbf | 2020-09-16 07:11:57 -0700 | [diff] [blame] | 712 | _, first_enum = cls._get_mixins_(cls, bases) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 713 | classdict = metacls.__prepare__(class_name, bases) |
| 714 | |
| 715 | # special processing needed for names? |
| 716 | if isinstance(names, str): |
| 717 | names = names.replace(',', ' ').split() |
Dong-hee Na | dcc8ce4 | 2017-06-22 01:52:32 +0900 | [diff] [blame] | 718 | if isinstance(names, (tuple, list)) and names and isinstance(names[0], str): |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 719 | original_names, names = names, [] |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 720 | last_values = [] |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 721 | for count, name in enumerate(original_names): |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 722 | value = first_enum._generate_next_value_(name, start, count, last_values[:]) |
| 723 | last_values.append(value) |
| 724 | names.append((name, value)) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 725 | |
| 726 | # Here, names is either an iterable of (name, value) or a mapping. |
| 727 | for item in names: |
| 728 | if isinstance(item, str): |
| 729 | member_name, member_value = item, names[item] |
| 730 | else: |
| 731 | member_name, member_value = item |
| 732 | classdict[member_name] = member_value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 733 | |
| 734 | # TODO: replace the frame hack if a blessed way to know the calling |
| 735 | # module is ever developed |
| 736 | if module is None: |
| 737 | try: |
| 738 | module = sys._getframe(2).f_globals['__name__'] |
Pablo Galindo | 293dd23 | 2019-11-19 21:34:03 +0000 | [diff] [blame] | 739 | except (AttributeError, ValueError, KeyError): |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 740 | pass |
| 741 | if module is None: |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 742 | _make_class_unpicklable(classdict) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 743 | else: |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 744 | classdict['__module__'] = module |
Ethan Furman | ca1b794 | 2014-02-08 11:36:27 -0800 | [diff] [blame] | 745 | if qualname is not None: |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 746 | classdict['__qualname__'] = qualname |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 747 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 748 | return metacls.__new__(metacls, class_name, bases, classdict, boundary=boundary) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 749 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 750 | def _convert_(cls, name, module, filter, source=None, boundary=None): |
orlnub123 | 0fb9fad | 2018-09-12 20:28:53 +0300 | [diff] [blame] | 751 | """ |
| 752 | Create a new Enum subclass that replaces a collection of global constants |
| 753 | """ |
| 754 | # convert all constants from source (or module) that pass filter() to |
| 755 | # a new Enum called name, and export the enum and its members back to |
| 756 | # module; |
| 757 | # also, replace the __reduce_ex__ method so unpickling works in |
| 758 | # previous Python versions |
| 759 | module_globals = vars(sys.modules[module]) |
| 760 | if source: |
| 761 | source = vars(source) |
| 762 | else: |
| 763 | source = module_globals |
| 764 | # _value2member_map_ is populated in the same order every time |
| 765 | # for a consistent reverse mapping of number to name when there |
| 766 | # are multiple names for the same number. |
| 767 | members = [ |
| 768 | (name, value) |
| 769 | for name, value in source.items() |
| 770 | if filter(name)] |
| 771 | try: |
| 772 | # sort by value |
| 773 | members.sort(key=lambda t: (t[1], t[0])) |
| 774 | except TypeError: |
| 775 | # unless some values aren't comparable, in which case sort by name |
| 776 | members.sort(key=lambda t: t[0]) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 777 | cls = cls(name, members, module=module, boundary=boundary or KEEP) |
orlnub123 | 0fb9fad | 2018-09-12 20:28:53 +0300 | [diff] [blame] | 778 | cls.__reduce_ex__ = _reduce_ex_by_name |
| 779 | module_globals.update(cls.__members__) |
| 780 | module_globals[name] = cls |
| 781 | return cls |
| 782 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 783 | @staticmethod |
Ethan Furman | 3064dbf | 2020-09-16 07:11:57 -0700 | [diff] [blame] | 784 | def _check_for_existing_members(class_name, bases): |
| 785 | for chain in bases: |
| 786 | for base in chain.__mro__: |
| 787 | if issubclass(base, Enum) and base._member_names_: |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 788 | raise TypeError( |
| 789 | "%s: cannot extend enumeration %r" |
| 790 | % (class_name, base.__name__) |
| 791 | ) |
Ethan Furman | 3064dbf | 2020-09-16 07:11:57 -0700 | [diff] [blame] | 792 | |
| 793 | @staticmethod |
| 794 | def _get_mixins_(class_name, bases): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 795 | """ |
| 796 | Returns the type for creating enum members, and the first inherited |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 797 | enum class. |
| 798 | |
| 799 | bases: the tuple of bases that was given to __new__ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 800 | """ |
| 801 | if not bases: |
| 802 | return object, Enum |
| 803 | |
Ethan Furman | 5bdab64 | 2018-09-21 19:03:09 -0700 | [diff] [blame] | 804 | def _find_data_type(bases): |
Ethan Furman | bff01f3 | 2020-09-15 15:56:26 -0700 | [diff] [blame] | 805 | data_types = [] |
Ethan Furman | 5bdab64 | 2018-09-21 19:03:09 -0700 | [diff] [blame] | 806 | for chain in bases: |
Ethan Furman | bff01f3 | 2020-09-15 15:56:26 -0700 | [diff] [blame] | 807 | candidate = None |
Ethan Furman | 5bdab64 | 2018-09-21 19:03:09 -0700 | [diff] [blame] | 808 | for base in chain.__mro__: |
| 809 | if base is object: |
| 810 | continue |
Ethan Furman | c266736 | 2020-12-07 00:17:31 -0800 | [diff] [blame] | 811 | elif issubclass(base, Enum): |
| 812 | if base._member_type_ is not object: |
| 813 | data_types.append(base._member_type_) |
| 814 | break |
Ethan Furman | 5bdab64 | 2018-09-21 19:03:09 -0700 | [diff] [blame] | 815 | elif '__new__' in base.__dict__: |
Ethan Furman | cd45385 | 2018-10-05 23:29:36 -0700 | [diff] [blame] | 816 | if issubclass(base, Enum): |
Ethan Furman | 5bdab64 | 2018-09-21 19:03:09 -0700 | [diff] [blame] | 817 | continue |
Ethan Furman | bff01f3 | 2020-09-15 15:56:26 -0700 | [diff] [blame] | 818 | data_types.append(candidate or base) |
| 819 | break |
Ethan Furman | c266736 | 2020-12-07 00:17:31 -0800 | [diff] [blame] | 820 | else: |
Ethan Furman | bff01f3 | 2020-09-15 15:56:26 -0700 | [diff] [blame] | 821 | candidate = base |
| 822 | if len(data_types) > 1: |
Ethan Furman | 3064dbf | 2020-09-16 07:11:57 -0700 | [diff] [blame] | 823 | raise TypeError('%r: too many data types: %r' % (class_name, data_types)) |
Ethan Furman | bff01f3 | 2020-09-15 15:56:26 -0700 | [diff] [blame] | 824 | elif data_types: |
| 825 | return data_types[0] |
| 826 | else: |
| 827 | return None |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 828 | |
Ethan Furman | 5bdab64 | 2018-09-21 19:03:09 -0700 | [diff] [blame] | 829 | # ensure final parent class is an Enum derivative, find any concrete |
| 830 | # data type, and check that Enum has no members |
| 831 | first_enum = bases[-1] |
| 832 | if not issubclass(first_enum, Enum): |
| 833 | raise TypeError("new enumerations should be created as " |
| 834 | "`EnumName([mixin_type, ...] [data_type,] enum_type)`") |
| 835 | member_type = _find_data_type(bases) or object |
| 836 | if first_enum._member_names_: |
| 837 | raise TypeError("Cannot extend enumerations") |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 838 | return member_type, first_enum |
| 839 | |
| 840 | @staticmethod |
| 841 | def _find_new_(classdict, member_type, first_enum): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 842 | """ |
| 843 | Returns the __new__ to be used for creating the enum members. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 844 | |
| 845 | classdict: the class dictionary given to __new__ |
| 846 | member_type: the data type whose __new__ will be used by default |
| 847 | first_enum: enumeration to check for an overriding __new__ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 848 | """ |
| 849 | # now find the correct __new__, checking to see of one was defined |
| 850 | # by the user; also check earlier enum classes in case a __new__ was |
| 851 | # saved as __new_member__ |
| 852 | __new__ = classdict.get('__new__', None) |
| 853 | |
| 854 | # should __new__ be saved as __new_member__ later? |
| 855 | save_new = __new__ is not None |
| 856 | |
| 857 | if __new__ is None: |
| 858 | # check all possibles for __new_member__ before falling back to |
| 859 | # __new__ |
| 860 | for method in ('__new_member__', '__new__'): |
| 861 | for possible in (member_type, first_enum): |
| 862 | target = getattr(possible, method, None) |
| 863 | if target not in { |
| 864 | None, |
| 865 | None.__new__, |
| 866 | object.__new__, |
| 867 | Enum.__new__, |
| 868 | }: |
| 869 | __new__ = target |
| 870 | break |
| 871 | if __new__ is not None: |
| 872 | break |
| 873 | else: |
| 874 | __new__ = object.__new__ |
| 875 | |
| 876 | # if a non-object.__new__ is used then whatever value/tuple was |
| 877 | # assigned to the enum member name will be passed to __new__ and to the |
| 878 | # new enum member's __init__ |
| 879 | if __new__ is object.__new__: |
| 880 | use_args = False |
| 881 | else: |
| 882 | use_args = True |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 883 | return __new__, save_new, use_args |
| 884 | |
| 885 | |
| 886 | class Enum(metaclass=EnumMeta): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 887 | """ |
| 888 | Generic enumeration. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 889 | |
| 890 | Derive from this class to define new enumerations. |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 891 | """ |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 892 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 893 | def __new__(cls, value): |
| 894 | # all enum instances are actually created during class construction |
| 895 | # without calling this method; this method is called by the metaclass' |
| 896 | # __call__ (i.e. Color(3) ), and by pickle |
| 897 | if type(value) is cls: |
Ethan Furman | 23bb6f4 | 2016-11-21 09:22:05 -0800 | [diff] [blame] | 898 | # For lookups like Color(Color.RED) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 899 | return value |
| 900 | # by-value search for a matching enum member |
| 901 | # see if it's in the reverse mapping (for hashable values) |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 902 | try: |
Andrew Svetlov | 34ae04f | 2018-12-26 20:45:33 +0200 | [diff] [blame] | 903 | return cls._value2member_map_[value] |
| 904 | except KeyError: |
| 905 | # Not found, no need to do long O(n) search |
| 906 | pass |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 907 | except TypeError: |
| 908 | # not there, now do long search -- O(n) behavior |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 909 | for member in cls._member_map_.values(): |
Ethan Furman | 0081f23 | 2014-09-16 17:31:23 -0700 | [diff] [blame] | 910 | if member._value_ == value: |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 911 | return member |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 912 | # still not found -- try _missing_ hook |
Ethan Furman | 019f0a0 | 2018-09-12 11:43:34 -0700 | [diff] [blame] | 913 | try: |
| 914 | exc = None |
| 915 | result = cls._missing_(value) |
| 916 | except Exception as e: |
| 917 | exc = e |
| 918 | result = None |
| 919 | if isinstance(result, cls): |
| 920 | return result |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 921 | elif ( |
| 922 | Flag is not None and issubclass(cls, Flag) |
| 923 | and cls._boundary_ is EJECT and isinstance(result, int) |
| 924 | ): |
| 925 | return result |
Ethan Furman | 019f0a0 | 2018-09-12 11:43:34 -0700 | [diff] [blame] | 926 | else: |
Walter Dörwald | 323842c | 2019-07-18 20:37:13 +0200 | [diff] [blame] | 927 | ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__)) |
Ethan Furman | 019f0a0 | 2018-09-12 11:43:34 -0700 | [diff] [blame] | 928 | if result is None and exc is None: |
| 929 | raise ve_exc |
| 930 | elif exc is None: |
| 931 | exc = TypeError( |
| 932 | 'error in %s._missing_: returned %r instead of None or a valid member' |
| 933 | % (cls.__name__, result) |
| 934 | ) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 935 | if not isinstance(exc, ValueError): |
| 936 | exc.__context__ = ve_exc |
Ethan Furman | 019f0a0 | 2018-09-12 11:43:34 -0700 | [diff] [blame] | 937 | raise exc |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 938 | |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 939 | def _generate_next_value_(name, start, count, last_values): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 940 | """ |
| 941 | Generate the next value when not given. |
| 942 | |
| 943 | name: the name of the member |
| 944 | start: the initial start value or None |
| 945 | count: the number of existing members |
| 946 | last_value: the last value assigned or None |
| 947 | """ |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 948 | for last_value in reversed(last_values): |
| 949 | try: |
| 950 | return last_value + 1 |
| 951 | except TypeError: |
| 952 | pass |
| 953 | else: |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 954 | return start |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 955 | |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 956 | @classmethod |
| 957 | def _missing_(cls, value): |
Ethan Furman | c95ad7a | 2020-09-16 10:26:50 -0700 | [diff] [blame] | 958 | return None |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 959 | |
| 960 | def __repr__(self): |
| 961 | return "<%s.%s: %r>" % ( |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 962 | self.__class__.__name__, self._name_, self._value_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 963 | |
| 964 | def __str__(self): |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 965 | return "%s.%s" % (self.__class__.__name__, self._name_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 966 | |
Ethan Furman | 388a392 | 2013-08-12 06:51:41 -0700 | [diff] [blame] | 967 | def __dir__(self): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 968 | """ |
| 969 | Returns all members and all public methods |
| 970 | """ |
Ethan Furman | 0ae550b | 2014-10-14 08:58:32 -0700 | [diff] [blame] | 971 | added_behavior = [ |
| 972 | m |
| 973 | for cls in self.__class__.mro() |
| 974 | for m in cls.__dict__ |
Ethan Furman | 354ecf1 | 2015-03-11 08:43:12 -0700 | [diff] [blame] | 975 | if m[0] != '_' and m not in self._member_map_ |
Angelin BOOZ | 68526fe | 2020-09-21 15:11:06 +0200 | [diff] [blame] | 976 | ] + [m for m in self.__dict__ if m[0] != '_'] |
Ethan Furman | ec5f8eb | 2014-10-21 13:40:35 -0700 | [diff] [blame] | 977 | return (['__class__', '__doc__', '__module__'] + added_behavior) |
Ethan Furman | 388a392 | 2013-08-12 06:51:41 -0700 | [diff] [blame] | 978 | |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 979 | def __format__(self, format_spec): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 980 | """ |
| 981 | Returns format using actual value type unless __str__ has been overridden. |
| 982 | """ |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 983 | # mixed-in Enums should use the mixed-in type's __format__, otherwise |
| 984 | # we can get strange results with the Enum name showing up instead of |
| 985 | # the value |
| 986 | |
thatneat | 2f19e82 | 2019-07-04 11:28:37 -0700 | [diff] [blame] | 987 | # pure Enum branch, or branch with __str__ explicitly overridden |
Ethan Furman | 37440ee | 2020-12-08 11:14:10 -0800 | [diff] [blame] | 988 | str_overridden = type(self).__str__ not in (Enum.__str__, Flag.__str__) |
thatneat | 2f19e82 | 2019-07-04 11:28:37 -0700 | [diff] [blame] | 989 | if self._member_type_ is object or str_overridden: |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 990 | cls = str |
| 991 | val = str(self) |
| 992 | # mix-in branch |
| 993 | else: |
| 994 | cls = self._member_type_ |
Ethan Furman | 0081f23 | 2014-09-16 17:31:23 -0700 | [diff] [blame] | 995 | val = self._value_ |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 996 | return cls.__format__(val, format_spec) |
| 997 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 998 | def __hash__(self): |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 999 | return hash(self._name_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1000 | |
Ethan Furman | ca1b794 | 2014-02-08 11:36:27 -0800 | [diff] [blame] | 1001 | def __reduce_ex__(self, proto): |
Ethan Furman | dc87052 | 2014-02-18 12:37:12 -0800 | [diff] [blame] | 1002 | return self.__class__, (self._value_, ) |
Ethan Furman | ca1b794 | 2014-02-08 11:36:27 -0800 | [diff] [blame] | 1003 | |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 1004 | # enum.property is used to provide access to the `name` and |
| 1005 | # `value` attributes of enum members while keeping some measure of |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1006 | # protection from modification, while still allowing for an enumeration |
| 1007 | # to have members named `name` and `value`. This works because enumeration |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 1008 | # members are not set directly on the enum class; they are kept in a |
| 1009 | # separate structure, _member_map_, which is where enum.property looks for |
| 1010 | # them |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1011 | |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 1012 | @property |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1013 | def name(self): |
Ethan Furman | c850f34 | 2013-09-15 16:59:35 -0700 | [diff] [blame] | 1014 | """The name of the Enum member.""" |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 1015 | return self._name_ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1016 | |
Ethan Furman | c314e60 | 2021-01-12 23:47:57 -0800 | [diff] [blame] | 1017 | @property |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1018 | def value(self): |
Ethan Furman | c850f34 | 2013-09-15 16:59:35 -0700 | [diff] [blame] | 1019 | """The value of the Enum member.""" |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 1020 | return self._value_ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1021 | |
| 1022 | |
| 1023 | class IntEnum(int, Enum): |
Ethan Furman | 0063ff4 | 2020-09-21 17:23:13 -0700 | [diff] [blame] | 1024 | """ |
| 1025 | Enum where members are also (and must be) ints |
| 1026 | """ |
| 1027 | |
| 1028 | |
| 1029 | class StrEnum(str, Enum): |
| 1030 | """ |
| 1031 | Enum where members are also (and must be) strings |
| 1032 | """ |
| 1033 | |
| 1034 | def __new__(cls, *values): |
| 1035 | if len(values) > 3: |
| 1036 | raise TypeError('too many arguments for str(): %r' % (values, )) |
| 1037 | if len(values) == 1: |
| 1038 | # it must be a string |
| 1039 | if not isinstance(values[0], str): |
| 1040 | raise TypeError('%r is not a string' % (values[0], )) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1041 | if len(values) >= 2: |
Ethan Furman | 0063ff4 | 2020-09-21 17:23:13 -0700 | [diff] [blame] | 1042 | # check that encoding argument is a string |
| 1043 | if not isinstance(values[1], str): |
| 1044 | raise TypeError('encoding must be a string, not %r' % (values[1], )) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1045 | if len(values) == 3: |
| 1046 | # check that errors argument is a string |
| 1047 | if not isinstance(values[2], str): |
| 1048 | raise TypeError('errors must be a string, not %r' % (values[2])) |
Ethan Furman | 0063ff4 | 2020-09-21 17:23:13 -0700 | [diff] [blame] | 1049 | value = str(*values) |
| 1050 | member = str.__new__(cls, value) |
| 1051 | member._value_ = value |
| 1052 | return member |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 1053 | |
Ethan Furman | d986d16 | 2020-09-22 13:00:07 -0700 | [diff] [blame] | 1054 | __str__ = str.__str__ |
| 1055 | |
Ethan Furman | efb13be | 2020-12-10 12:20:06 -0800 | [diff] [blame] | 1056 | def _generate_next_value_(name, start, count, last_values): |
| 1057 | """ |
| 1058 | Return the lower-cased version of the member name. |
| 1059 | """ |
| 1060 | return name.lower() |
| 1061 | |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 1062 | |
Ethan Furman | 24e837f | 2015-03-18 17:27:57 -0700 | [diff] [blame] | 1063 | def _reduce_ex_by_name(self, proto): |
| 1064 | return self.name |
| 1065 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1066 | class FlagBoundary(StrEnum): |
| 1067 | """ |
| 1068 | control how out of range values are handled |
| 1069 | "strict" -> error is raised [default for Flag] |
| 1070 | "conform" -> extra bits are discarded |
| 1071 | "eject" -> lose flag status [default for IntFlag] |
| 1072 | "keep" -> keep flag status and all bits |
| 1073 | """ |
| 1074 | STRICT = auto() |
| 1075 | CONFORM = auto() |
| 1076 | EJECT = auto() |
| 1077 | KEEP = auto() |
| 1078 | STRICT, CONFORM, EJECT, KEEP = FlagBoundary |
| 1079 | |
| 1080 | |
| 1081 | class Flag(Enum, boundary=STRICT): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1082 | """ |
| 1083 | Support for flags |
| 1084 | """ |
Ethan Furman | c16595e | 2016-09-10 23:36:59 -0700 | [diff] [blame] | 1085 | |
| 1086 | def _generate_next_value_(name, start, count, last_values): |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1087 | """ |
| 1088 | Generate the next value when not given. |
| 1089 | |
| 1090 | name: the name of the member |
HongWeipeng | bb16fb2 | 2019-09-21 13:22:54 +0800 | [diff] [blame] | 1091 | start: the initial start value or None |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1092 | count: the number of existing members |
| 1093 | last_value: the last value assigned or None |
| 1094 | """ |
| 1095 | if not count: |
| 1096 | return start if start is not None else 1 |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1097 | last_value = max(last_values) |
| 1098 | try: |
| 1099 | high_bit = _high_bit(last_value) |
| 1100 | except Exception: |
| 1101 | raise TypeError('Invalid Flag value: %r' % last_value) from None |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1102 | return 2 ** (high_bit+1) |
| 1103 | |
| 1104 | @classmethod |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1105 | def _iter_member_by_value_(cls, value): |
| 1106 | """ |
| 1107 | Extract all members from the value in definition (i.e. increasing value) order. |
| 1108 | """ |
| 1109 | for val in _iter_bits_lsb(value & cls._flag_mask_): |
| 1110 | yield cls._value2member_map_.get(val) |
| 1111 | |
| 1112 | _iter_member_ = _iter_member_by_value_ |
| 1113 | |
| 1114 | @classmethod |
| 1115 | def _iter_member_by_def_(cls, value): |
| 1116 | """ |
| 1117 | Extract all members from the value in definition order. |
| 1118 | """ |
| 1119 | yield from sorted( |
| 1120 | cls._iter_member_by_value_(value), |
| 1121 | key=lambda m: m._sort_order_, |
| 1122 | ) |
| 1123 | |
| 1124 | @classmethod |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1125 | def _missing_(cls, value): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1126 | """ |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 1127 | Create a composite member iff value contains only members. |
| 1128 | """ |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1129 | if not isinstance(value, int): |
| 1130 | raise ValueError( |
| 1131 | "%r is not a valid %s" % (value, cls.__qualname__) |
| 1132 | ) |
| 1133 | # check boundaries |
| 1134 | # - value must be in range (e.g. -16 <-> +15, i.e. ~15 <-> 15) |
| 1135 | # - value must not include any skipped flags (e.g. if bit 2 is not |
| 1136 | # defined, then 0d10 is invalid) |
| 1137 | flag_mask = cls._flag_mask_ |
| 1138 | all_bits = cls._all_bits_ |
| 1139 | neg_value = None |
| 1140 | if ( |
| 1141 | not ~all_bits <= value <= all_bits |
| 1142 | or value & (all_bits ^ flag_mask) |
| 1143 | ): |
| 1144 | if cls._boundary_ is STRICT: |
| 1145 | max_bits = max(value.bit_length(), flag_mask.bit_length()) |
| 1146 | raise ValueError( |
| 1147 | "%s: invalid value: %r\n given %s\n allowed %s" % ( |
| 1148 | cls.__name__, value, bin(value, max_bits), bin(flag_mask, max_bits), |
| 1149 | )) |
| 1150 | elif cls._boundary_ is CONFORM: |
| 1151 | value = value & flag_mask |
| 1152 | elif cls._boundary_ is EJECT: |
| 1153 | return value |
| 1154 | elif cls._boundary_ is KEEP: |
| 1155 | if value < 0: |
| 1156 | value = ( |
| 1157 | max(all_bits+1, 2**(value.bit_length())) |
| 1158 | + value |
| 1159 | ) |
| 1160 | else: |
| 1161 | raise ValueError( |
| 1162 | 'unknown flag boundary: %r' % (cls._boundary_, ) |
| 1163 | ) |
| 1164 | if value < 0: |
| 1165 | neg_value = value |
| 1166 | value = all_bits + 1 + value |
| 1167 | # get members and unknown |
| 1168 | unknown = value & ~flag_mask |
| 1169 | member_value = value & flag_mask |
| 1170 | if unknown and cls._boundary_ is not KEEP: |
| 1171 | raise ValueError( |
| 1172 | '%s(%r) --> unknown values %r [%s]' |
| 1173 | % (cls.__name__, value, unknown, bin(unknown)) |
| 1174 | ) |
| 1175 | # normal Flag? |
| 1176 | __new__ = getattr(cls, '__new_member__', None) |
| 1177 | if cls._member_type_ is object and not __new__: |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 1178 | # construct a singleton enum pseudo-member |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1179 | pseudo_member = object.__new__(cls) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1180 | else: |
| 1181 | pseudo_member = (__new__ or cls._member_type_.__new__)(cls, value) |
| 1182 | if not hasattr(pseudo_member, 'value'): |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1183 | pseudo_member._value_ = value |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1184 | if member_value: |
| 1185 | pseudo_member._name_ = '|'.join([ |
| 1186 | m._name_ for m in cls._iter_member_(member_value) |
| 1187 | ]) |
| 1188 | if unknown: |
| 1189 | pseudo_member._name_ += '|0x%x' % unknown |
| 1190 | else: |
| 1191 | pseudo_member._name_ = None |
| 1192 | # use setdefault in case another thread already created a composite |
| 1193 | # with this value, but only if all members are known |
| 1194 | # note: zero is a special case -- add it |
| 1195 | if not unknown: |
Ethan Furman | 28cf663 | 2017-01-24 12:12:06 -0800 | [diff] [blame] | 1196 | pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1197 | if neg_value is not None: |
| 1198 | cls._value2member_map_[neg_value] = pseudo_member |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1199 | return pseudo_member |
| 1200 | |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1201 | def __contains__(self, other): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1202 | """ |
| 1203 | Returns True if self has at least the same flags set as other. |
| 1204 | """ |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1205 | if not isinstance(other, self.__class__): |
Rahul Jha | 9430652 | 2018-09-10 23:51:04 +0530 | [diff] [blame] | 1206 | raise TypeError( |
| 1207 | "unsupported operand type(s) for 'in': '%s' and '%s'" % ( |
| 1208 | type(other).__qualname__, self.__class__.__qualname__)) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1209 | if other._value_ == 0 or self._value_ == 0: |
| 1210 | return False |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1211 | return other._value_ & self._value_ == other._value_ |
| 1212 | |
Ethan Furman | 7219e27 | 2020-09-16 13:01:00 -0700 | [diff] [blame] | 1213 | def __iter__(self): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1214 | """ |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1215 | Returns flags in definition order. |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1216 | """ |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1217 | yield from self._iter_member_(self._value_) |
| 1218 | |
| 1219 | def __len__(self): |
| 1220 | return self._value_.bit_count() |
Ethan Furman | 7219e27 | 2020-09-16 13:01:00 -0700 | [diff] [blame] | 1221 | |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1222 | def __repr__(self): |
| 1223 | cls = self.__class__ |
| 1224 | if self._name_ is not None: |
| 1225 | return '<%s.%s: %r>' % (cls.__name__, self._name_, self._value_) |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1226 | else: |
| 1227 | # only zero is unnamed by default |
| 1228 | return '<%s: %r>' % (cls.__name__, self._value_) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1229 | |
| 1230 | def __str__(self): |
| 1231 | cls = self.__class__ |
| 1232 | if self._name_ is not None: |
| 1233 | return '%s.%s' % (cls.__name__, self._name_) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1234 | else: |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1235 | return '%s(%s)' % (cls.__name__, self._value_) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1236 | |
Ethan Furman | 25d94bb | 2016-09-02 16:32:32 -0700 | [diff] [blame] | 1237 | def __bool__(self): |
| 1238 | return bool(self._value_) |
| 1239 | |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1240 | def __or__(self, other): |
| 1241 | if not isinstance(other, self.__class__): |
| 1242 | return NotImplemented |
| 1243 | return self.__class__(self._value_ | other._value_) |
| 1244 | |
| 1245 | def __and__(self, other): |
| 1246 | if not isinstance(other, self.__class__): |
| 1247 | return NotImplemented |
| 1248 | return self.__class__(self._value_ & other._value_) |
| 1249 | |
| 1250 | def __xor__(self, other): |
| 1251 | if not isinstance(other, self.__class__): |
| 1252 | return NotImplemented |
| 1253 | return self.__class__(self._value_ ^ other._value_) |
| 1254 | |
| 1255 | def __invert__(self): |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1256 | if self._inverted_ is None: |
| 1257 | if self._boundary_ is KEEP: |
| 1258 | # use all bits |
| 1259 | self._inverted_ = self.__class__(~self._value_) |
| 1260 | else: |
| 1261 | # calculate flags not in this member |
| 1262 | self._inverted_ = self.__class__(self._flag_mask_ ^ self._value_) |
| 1263 | self._inverted_._inverted_ = self |
| 1264 | return self._inverted_ |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1265 | |
| 1266 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1267 | class IntFlag(int, Flag, boundary=EJECT): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1268 | """ |
| 1269 | Support for integer-based Flags |
| 1270 | """ |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1271 | |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1272 | def __or__(self, other): |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1273 | if isinstance(other, self.__class__): |
| 1274 | other = other._value_ |
| 1275 | elif isinstance(other, int): |
| 1276 | other = other |
| 1277 | else: |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1278 | return NotImplemented |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1279 | value = self._value_ |
| 1280 | return self.__class__(value | other) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1281 | |
| 1282 | def __and__(self, other): |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1283 | if isinstance(other, self.__class__): |
| 1284 | other = other._value_ |
| 1285 | elif isinstance(other, int): |
| 1286 | other = other |
| 1287 | else: |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1288 | return NotImplemented |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1289 | value = self._value_ |
| 1290 | return self.__class__(value & other) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1291 | |
| 1292 | def __xor__(self, other): |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1293 | if isinstance(other, self.__class__): |
| 1294 | other = other._value_ |
| 1295 | elif isinstance(other, int): |
| 1296 | other = other |
| 1297 | else: |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1298 | return NotImplemented |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1299 | value = self._value_ |
| 1300 | return self.__class__(value ^ other) |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1301 | |
| 1302 | __ror__ = __or__ |
| 1303 | __rand__ = __and__ |
| 1304 | __rxor__ = __xor__ |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1305 | __invert__ = Flag.__invert__ |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1306 | |
| 1307 | def _high_bit(value): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1308 | """ |
| 1309 | returns index of highest bit, or -1 if value is zero or negative |
| 1310 | """ |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 1311 | return value.bit_length() - 1 |
Ethan Furman | ee47e5c | 2016-08-31 00:12:15 -0700 | [diff] [blame] | 1312 | |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 1313 | def unique(enumeration): |
Ethan Furman | 6d3dfee | 2020-12-08 12:26:56 -0800 | [diff] [blame] | 1314 | """ |
| 1315 | Class decorator for enumerations ensuring unique member values. |
| 1316 | """ |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 1317 | duplicates = [] |
| 1318 | for name, member in enumeration.__members__.items(): |
| 1319 | if name != member.name: |
| 1320 | duplicates.append((name, member.name)) |
| 1321 | if duplicates: |
| 1322 | alias_details = ', '.join( |
| 1323 | ["%s -> %s" % (alias, name) for (alias, name) in duplicates]) |
| 1324 | raise ValueError('duplicate values found in %r: %s' % |
| 1325 | (enumeration, alias_details)) |
| 1326 | return enumeration |
Ethan Furman | 3515dcc | 2016-09-18 13:15:41 -0700 | [diff] [blame] | 1327 | |
Ethan Furman | 7aaeb2a | 2021-01-25 14:26:19 -0800 | [diff] [blame] | 1328 | def _power_of_two(value): |
| 1329 | if value < 1: |
| 1330 | return False |
| 1331 | return value == 2 ** _high_bit(value) |