| 1 |
import sys |
| 2 |
import builtins as bltns |
| 3 |
from types import MappingProxyType, DynamicClassAttribute |
| 4 |
from operator import or_ as _or_ |
| 5 |
from functools import reduce |
| 6 |
|
| 7 |
|
| 8 |
__all__ = [ |
| 9 |
'EnumType', 'EnumMeta', |
| 10 |
'Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag', 'ReprEnum', |
| 11 |
'auto', 'unique', 'property', 'verify', 'member', 'nonmember', |
| 12 |
'FlagBoundary', 'STRICT', 'CONFORM', 'EJECT', 'KEEP', |
| 13 |
'global_flag_repr', 'global_enum_repr', 'global_str', 'global_enum', |
| 14 |
'EnumCheck', 'CONTINUOUS', 'NAMED_FLAGS', 'UNIQUE', |
| 15 |
'pickle_by_global_name', 'pickle_by_enum_name', |
| 16 |
] |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
Enum = Flag = EJECT = _stdlib_enums = ReprEnum = None |
| 23 |
|
| 24 |
class nonmember(object): |
| 25 |
""" |
| 26 |
Protects item from becoming an Enum member during class creation. |
| 27 |
""" |
| 28 |
def __init__(self, value): |
| 29 |
self.value = value |
| 30 |
|
| 31 |
class member(object): |
| 32 |
""" |
| 33 |
Forces item to become an Enum member during class creation. |
| 34 |
""" |
| 35 |
def __init__(self, value): |
| 36 |
self.value = value |
| 37 |
|
| 38 |
def _is_descriptor(obj): |
| 39 |
""" |
| 40 |
Returns True if obj is a descriptor, False otherwise. |
| 41 |
""" |
| 42 |
return ( |
| 43 |
hasattr(obj, '__get__') or |
| 44 |
hasattr(obj, '__set__') or |
| 45 |
hasattr(obj, '__delete__') |
| 46 |
) |
| 47 |
|
| 48 |
def _is_dunder(name): |
| 49 |
""" |
| 50 |
Returns True if a __dunder__ name, False otherwise. |
| 51 |
""" |
| 52 |
return ( |
| 53 |
len(name) > 4 and |
| 54 |
name[:2] == name[-2:] == '__' and |
| 55 |
name[2] != '_' and |
| 56 |
name[-3] != '_' |
| 57 |
) |
| 58 |
|
| 59 |
def _is_sunder(name): |
| 60 |
""" |
| 61 |
Returns True if a _sunder_ name, False otherwise. |
| 62 |
""" |
| 63 |
return ( |
| 64 |
len(name) > 2 and |
| 65 |
name[0] == name[-1] == '_' and |
| 66 |
name[1:2] != '_' and |
| 67 |
name[-2:-1] != '_' |
| 68 |
) |
| 69 |
|
| 70 |
def _is_internal_class(cls_name, obj): |
| 71 |
|
| 72 |
if not isinstance(obj, type): |
| 73 |
return False |
| 74 |
qualname = getattr(obj, '__qualname__', '') |
| 75 |
s_pattern = cls_name + '.' + getattr(obj, '__name__', '') |
| 76 |
e_pattern = '.' + s_pattern |
| 77 |
return qualname == s_pattern or qualname.endswith(e_pattern) |
| 78 |
|
| 79 |
def _is_private(cls_name, name): |
| 80 |
|
| 81 |
pattern = '_%s__' % (cls_name, ) |
| 82 |
pat_len = len(pattern) |
| 83 |
if ( |
| 84 |
len(name) > pat_len |
| 85 |
and name.startswith(pattern) |
| 86 |
and name[pat_len:pat_len+1] != ['_'] |
| 87 |
and (name[-1] != '_' or name[-2] != '_') |
| 88 |
): |
| 89 |
return True |
| 90 |
else: |
| 91 |
return False |
| 92 |
|
| 93 |
def _is_single_bit(num): |
| 94 |
""" |
| 95 |
True if only one bit set in num (should be an int) |
| 96 |
""" |
| 97 |
if num == 0: |
| 98 |
return False |
| 99 |
num &= num - 1 |
| 100 |
return num == 0 |
| 101 |
|
| 102 |
def _make_class_unpicklable(obj): |
| 103 |
""" |
| 104 |
Make the given obj un-picklable. |
| 105 |
|
| 106 |
obj should be either a dictionary, or an Enum |
| 107 |
""" |
| 108 |
def _break_on_call_reduce(self, proto): |
| 109 |
raise TypeError('%r cannot be pickled' % self) |
| 110 |
if isinstance(obj, dict): |
| 111 |
obj['__reduce_ex__'] = _break_on_call_reduce |
| 112 |
obj['__module__'] = '<unknown>' |
| 113 |
else: |
| 114 |
setattr(obj, '__reduce_ex__', _break_on_call_reduce) |
| 115 |
setattr(obj, '__module__', '<unknown>') |
| 116 |
|
| 117 |
def _iter_bits_lsb(num): |
| 118 |
|
| 119 |
original = num |
| 120 |
if isinstance(num, Enum): |
| 121 |
num = num.value |
| 122 |
if num < 0: |
| 123 |
raise ValueError('%r is not a positive integer' % original) |
| 124 |
while num: |
| 125 |
b = num & (~num + 1) |
| 126 |
yield b |
| 127 |
num ^= b |
| 128 |
|
| 129 |
def show_flag_values(value): |
| 130 |
return list(_iter_bits_lsb(value)) |
| 131 |
|
| 132 |
def bin(num, max_bits=None): |
| 133 |
""" |
| 134 |
Like built-in bin(), except negative values are represented in |
| 135 |
twos-compliment, and the leading bit always indicates sign |
| 136 |
(0=positive, 1=negative). |
| 137 |
|
| 138 |
>>> bin(10) |
| 139 |
'0b0 1010' |
| 140 |
>>> bin(~10) # ~10 is -11 |
| 141 |
'0b1 0101' |
| 142 |
""" |
| 143 |
|
| 144 |
ceiling = 2 ** (num).bit_length() |
| 145 |
if num >= 0: |
| 146 |
s = bltns.bin(num + ceiling).replace('1', '0', 1) |
| 147 |
else: |
| 148 |
s = bltns.bin(~num ^ (ceiling - 1) + ceiling) |
| 149 |
sign = s[:3] |
| 150 |
digits = s[3:] |
| 151 |
if max_bits is not None: |
| 152 |
if len(digits) < max_bits: |
| 153 |
digits = (sign[-1] * max_bits + digits)[-max_bits:] |
| 154 |
return "%s %s" % (sign, digits) |
| 155 |
|
| 156 |
def _dedent(text): |
| 157 |
""" |
| 158 |
Like textwrap.dedent. Rewritten because we cannot import textwrap. |
| 159 |
""" |
| 160 |
lines = text.split('\n') |
| 161 |
blanks = 0 |
| 162 |
for i, ch in enumerate(lines[0]): |
| 163 |
if ch != ' ': |
| 164 |
break |
| 165 |
for j, l in enumerate(lines): |
| 166 |
lines[j] = l[i:] |
| 167 |
return '\n'.join(lines) |
| 168 |
|
| 169 |
class _auto_null: |
| 170 |
def __repr__(self): |
| 171 |
return '_auto_null' |
| 172 |
_auto_null = _auto_null() |
| 173 |
|
| 174 |
class auto: |
| 175 |
""" |
| 176 |
Instances are replaced with an appropriate value in Enum class suites. |
| 177 |
""" |
| 178 |
def __init__(self, value=_auto_null): |
| 179 |
self.value = value |
| 180 |
|
| 181 |
def __repr__(self): |
| 182 |
return "auto(%r)" % self.value |
| 183 |
|
| 184 |
class property(DynamicClassAttribute): |
| 185 |
""" |
| 186 |
This is a descriptor, used to define attributes that act differently |
| 187 |
when accessed through an enum member and through an enum class. |
| 188 |
Instance access is the same as property(), but access to an attribute |
| 189 |
through the enum class will instead look in the class' _member_map_ for |
| 190 |
a corresponding enum member. |
| 191 |
""" |
| 192 |
|
| 193 |
def __get__(self, instance, ownerclass=None): |
| 194 |
if instance is None: |
| 195 |
try: |
| 196 |
return ownerclass._member_map_[self.name] |
| 197 |
except KeyError: |
| 198 |
raise AttributeError( |
| 199 |
'%r has no attribute %r' % (ownerclass, self.name) |
| 200 |
) |
| 201 |
else: |
| 202 |
if self.fget is None: |
| 203 |
|
| 204 |
try: |
| 205 |
return ownerclass._member_map_[self.name] |
| 206 |
except KeyError: |
| 207 |
raise AttributeError( |
| 208 |
'%r has no attribute %r' % (ownerclass, self.name) |
| 209 |
) from None |
| 210 |
else: |
| 211 |
return self.fget(instance) |
| 212 |
|
| 213 |
def __set__(self, instance, value): |
| 214 |
if self.fset is None: |
| 215 |
raise AttributeError( |
| 216 |
"<enum %r> cannot set attribute %r" % (self.clsname, self.name) |
| 217 |
) |
| 218 |
else: |
| 219 |
return self.fset(instance, value) |
| 220 |
|
| 221 |
def __delete__(self, instance): |
| 222 |
if self.fdel is None: |
| 223 |
raise AttributeError( |
| 224 |
"<enum %r> cannot delete attribute %r" % (self.clsname, self.name) |
| 225 |
) |
| 226 |
else: |
| 227 |
return self.fdel(instance) |
| 228 |
|
| 229 |
def __set_name__(self, ownerclass, name): |
| 230 |
self.name = name |
| 231 |
self.clsname = ownerclass.__name__ |
| 232 |
|
| 233 |
|
| 234 |
class _proto_member: |
| 235 |
""" |
| 236 |
intermediate step for enum members between class execution and final creation |
| 237 |
""" |
| 238 |
|
| 239 |
def __init__(self, value): |
| 240 |
self.value = value |
| 241 |
|
| 242 |
def __set_name__(self, enum_class, member_name): |
| 243 |
""" |
| 244 |
convert each quasi-member into an instance of the new enum class |
| 245 |
""" |
| 246 |
|
| 247 |
delattr(enum_class, member_name) |
| 248 |
|
| 249 |
value = self.value |
| 250 |
if not isinstance(value, tuple): |
| 251 |
args = (value, ) |
| 252 |
else: |
| 253 |
args = value |
| 254 |
if enum_class._member_type_ is tuple: |
| 255 |
args = (args, ) |
| 256 |
if not enum_class._use_args_: |
| 257 |
enum_member = enum_class._new_member_(enum_class) |
| 258 |
else: |
| 259 |
enum_member = enum_class._new_member_(enum_class, *args) |
| 260 |
if not hasattr(enum_member, '_value_'): |
| 261 |
if enum_class._member_type_ is object: |
| 262 |
enum_member._value_ = value |
| 263 |
else: |
| 264 |
try: |
| 265 |
enum_member._value_ = enum_class._member_type_(*args) |
| 266 |
except Exception as exc: |
| 267 |
new_exc = TypeError( |
| 268 |
'_value_ not set in __new__, unable to create it' |
| 269 |
) |
| 270 |
new_exc.__cause__ = exc |
| 271 |
raise new_exc |
| 272 |
value = enum_member._value_ |
| 273 |
enum_member._name_ = member_name |
| 274 |
enum_member.__objclass__ = enum_class |
| 275 |
enum_member.__init__(*args) |
| 276 |
enum_member._sort_order_ = len(enum_class._member_names_) |
| 277 |
|
| 278 |
if Flag is not None and issubclass(enum_class, Flag): |
| 279 |
if isinstance(value, int): |
| 280 |
enum_class._flag_mask_ |= value |
| 281 |
if _is_single_bit(value): |
| 282 |
enum_class._singles_mask_ |= value |
| 283 |
enum_class._all_bits_ = 2 ** ((enum_class._flag_mask_).bit_length()) - 1 |
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
try: |
| 288 |
try: |
| 289 |
|
| 290 |
enum_member = enum_class._value2member_map_[value] |
| 291 |
except TypeError: |
| 292 |
for name, canonical_member in enum_class._member_map_.items(): |
| 293 |
if canonical_member._value_ == value: |
| 294 |
enum_member = canonical_member |
| 295 |
break |
| 296 |
else: |
| 297 |
raise KeyError |
| 298 |
except KeyError: |
| 299 |
|
| 300 |
|
| 301 |
if ( |
| 302 |
Flag is None |
| 303 |
or not issubclass(enum_class, Flag) |
| 304 |
): |
| 305 |
|
| 306 |
enum_class._member_names_.append(member_name) |
| 307 |
elif ( |
| 308 |
Flag is not None |
| 309 |
and issubclass(enum_class, Flag) |
| 310 |
and isinstance(value, int) |
| 311 |
and _is_single_bit(value) |
| 312 |
): |
| 313 |
|
| 314 |
enum_class._member_names_.append(member_name) |
| 315 |
|
| 316 |
found_descriptor = None |
| 317 |
for base in enum_class.__mro__[1:]: |
| 318 |
descriptor = base.__dict__.get(member_name) |
| 319 |
if descriptor is not None: |
| 320 |
if isinstance(descriptor, (property, DynamicClassAttribute)): |
| 321 |
found_descriptor = descriptor |
| 322 |
break |
| 323 |
elif ( |
| 324 |
hasattr(descriptor, 'fget') and |
| 325 |
hasattr(descriptor, 'fset') and |
| 326 |
hasattr(descriptor, 'fdel') |
| 327 |
): |
| 328 |
found_descriptor = descriptor |
| 329 |
continue |
| 330 |
if found_descriptor: |
| 331 |
redirect = property() |
| 332 |
redirect.member = enum_member |
| 333 |
redirect.__set_name__(enum_class, member_name) |
| 334 |
|
| 335 |
redirect.fget = found_descriptor.fget |
| 336 |
redirect.fset = found_descriptor.fset |
| 337 |
redirect.fdel = found_descriptor.fdel |
| 338 |
setattr(enum_class, member_name, redirect) |
| 339 |
else: |
| 340 |
setattr(enum_class, member_name, enum_member) |
| 341 |
|
| 342 |
enum_class._member_map_[member_name] = enum_member |
| 343 |
try: |
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
enum_class._value2member_map_.setdefault(value, enum_member) |
| 348 |
except TypeError: |
| 349 |
|
| 350 |
enum_class._unhashable_values_.append(value) |
| 351 |
|
| 352 |
|
| 353 |
class _EnumDict(dict): |
| 354 |
""" |
| 355 |
Track enum member order and ensure member names are not reused. |
| 356 |
|
| 357 |
EnumType will use the names found in self._member_names as the |
| 358 |
enumeration member names. |
| 359 |
""" |
| 360 |
def __init__(self): |
| 361 |
super().__init__() |
| 362 |
self._member_names = {} |
| 363 |
self._last_values = [] |
| 364 |
self._ignore = [] |
| 365 |
self._auto_called = False |
| 366 |
|
| 367 |
def __setitem__(self, key, value): |
| 368 |
""" |
| 369 |
Changes anything not dundered or not a descriptor. |
| 370 |
|
| 371 |
If an enum member name is used twice, an error is raised; duplicate |
| 372 |
values are not checked for. |
| 373 |
|
| 374 |
Single underscore (sunder) names are reserved. |
| 375 |
""" |
| 376 |
if _is_internal_class(self._cls_name, value): |
| 377 |
import warnings |
| 378 |
warnings.warn( |
| 379 |
"In 3.13 classes created inside an enum will not become a member. " |
| 380 |
"Use the `member` decorator to keep the current behavior.", |
| 381 |
DeprecationWarning, |
| 382 |
stacklevel=2, |
| 383 |
) |
| 384 |
if _is_private(self._cls_name, key): |
| 385 |
|
| 386 |
pass |
| 387 |
elif _is_sunder(key): |
| 388 |
if key not in ( |
| 389 |
'_order_', |
| 390 |
'_generate_next_value_', '_numeric_repr_', '_missing_', '_ignore_', |
| 391 |
'_iter_member_', '_iter_member_by_value_', '_iter_member_by_def_', |
| 392 |
): |
| 393 |
raise ValueError( |
| 394 |
'_sunder_ names, such as %r, are reserved for future Enum use' |
| 395 |
% (key, ) |
| 396 |
) |
| 397 |
if key == '_generate_next_value_': |
| 398 |
|
| 399 |
if self._auto_called: |
| 400 |
raise TypeError("_generate_next_value_ must be defined before members") |
| 401 |
_gnv = value.__func__ if isinstance(value, staticmethod) else value |
| 402 |
setattr(self, '_generate_next_value', _gnv) |
| 403 |
elif key == '_ignore_': |
| 404 |
if isinstance(value, str): |
| 405 |
value = value.replace(',',' ').split() |
| 406 |
else: |
| 407 |
value = list(value) |
| 408 |
self._ignore = value |
| 409 |
already = set(value) & set(self._member_names) |
| 410 |
if already: |
| 411 |
raise ValueError( |
| 412 |
'_ignore_ cannot specify already set names: %r' |
| 413 |
% (already, ) |
| 414 |
) |
| 415 |
elif _is_dunder(key): |
| 416 |
if key == '__order__': |
| 417 |
key = '_order_' |
| 418 |
elif key in self._member_names: |
| 419 |
|
| 420 |
raise TypeError('%r already defined as %r' % (key, self[key])) |
| 421 |
elif key in self._ignore: |
| 422 |
pass |
| 423 |
elif isinstance(value, nonmember): |
| 424 |
|
| 425 |
value = value.value |
| 426 |
elif _is_descriptor(value): |
| 427 |
pass |
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
else: |
| 433 |
if key in self: |
| 434 |
|
| 435 |
raise TypeError('%r already defined as %r' % (key, self[key])) |
| 436 |
elif isinstance(value, member): |
| 437 |
|
| 438 |
value = value.value |
| 439 |
non_auto_store = True |
| 440 |
single = False |
| 441 |
if isinstance(value, auto): |
| 442 |
single = True |
| 443 |
value = (value, ) |
| 444 |
if type(value) is tuple and any(isinstance(v, auto) for v in value): |
| 445 |
|
| 446 |
|
| 447 |
auto_valued = [] |
| 448 |
for v in value: |
| 449 |
if isinstance(v, auto): |
| 450 |
non_auto_store = False |
| 451 |
if v.value == _auto_null: |
| 452 |
v.value = self._generate_next_value( |
| 453 |
key, 1, len(self._member_names), self._last_values[:], |
| 454 |
) |
| 455 |
self._auto_called = True |
| 456 |
v = v.value |
| 457 |
self._last_values.append(v) |
| 458 |
auto_valued.append(v) |
| 459 |
if single: |
| 460 |
value = auto_valued[0] |
| 461 |
else: |
| 462 |
value = tuple(auto_valued) |
| 463 |
self._member_names[key] = None |
| 464 |
if non_auto_store: |
| 465 |
self._last_values.append(value) |
| 466 |
super().__setitem__(key, value) |
| 467 |
|
| 468 |
def update(self, members, **more_members): |
| 469 |
try: |
| 470 |
for name in members.keys(): |
| 471 |
self[name] = members[name] |
| 472 |
except AttributeError: |
| 473 |
for name, value in members: |
| 474 |
self[name] = value |
| 475 |
for name, value in more_members.items(): |
| 476 |
self[name] = value |
| 477 |
|
| 478 |
|
| 479 |
class EnumType(type): |
| 480 |
""" |
| 481 |
Metaclass for Enum |
| 482 |
""" |
| 483 |
|
| 484 |
@classmethod |
| 485 |
def __prepare__(metacls, cls, bases, **kwds): |
| 486 |
|
| 487 |
metacls._check_for_existing_members_(cls, bases) |
| 488 |
|
| 489 |
enum_dict = _EnumDict() |
| 490 |
enum_dict._cls_name = cls |
| 491 |
|
| 492 |
member_type, first_enum = metacls._get_mixins_(cls, bases) |
| 493 |
if first_enum is not None: |
| 494 |
enum_dict['_generate_next_value_'] = getattr( |
| 495 |
first_enum, '_generate_next_value_', None, |
| 496 |
) |
| 497 |
return enum_dict |
| 498 |
|
| 499 |
def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **kwds): |
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
if _simple: |
| 506 |
return super().__new__(metacls, cls, bases, classdict, **kwds) |
| 507 |
|
| 508 |
|
| 509 |
classdict.setdefault('_ignore_', []).append('_ignore_') |
| 510 |
ignore = classdict['_ignore_'] |
| 511 |
for key in ignore: |
| 512 |
classdict.pop(key, None) |
| 513 |
|
| 514 |
|
| 515 |
member_names = classdict._member_names |
| 516 |
|
| 517 |
|
| 518 |
invalid_names = set(member_names) & {'mro', ''} |
| 519 |
if invalid_names: |
| 520 |
raise ValueError('invalid enum member name(s) %s' % ( |
| 521 |
','.join(repr(n) for n in invalid_names) |
| 522 |
)) |
| 523 |
|
| 524 |
|
| 525 |
_order_ = classdict.pop('_order_', None) |
| 526 |
|
| 527 |
classdict = dict(classdict.items()) |
| 528 |
|
| 529 |
|
| 530 |
member_type, first_enum = metacls._get_mixins_(cls, bases) |
| 531 |
__new__, save_new, use_args = metacls._find_new_( |
| 532 |
classdict, member_type, first_enum, |
| 533 |
) |
| 534 |
classdict['_new_member_'] = __new__ |
| 535 |
classdict['_use_args_'] = use_args |
| 536 |
|
| 537 |
|
| 538 |
for name in member_names: |
| 539 |
value = classdict[name] |
| 540 |
classdict[name] = _proto_member(value) |
| 541 |
|
| 542 |
|
| 543 |
classdict['_member_names_'] = [] |
| 544 |
classdict['_member_map_'] = {} |
| 545 |
classdict['_value2member_map_'] = {} |
| 546 |
classdict['_unhashable_values_'] = [] |
| 547 |
classdict['_member_type_'] = member_type |
| 548 |
|
| 549 |
classdict['_value_repr_'] = metacls._find_data_repr_(cls, bases) |
| 550 |
|
| 551 |
|
| 552 |
classdict['_boundary_'] = ( |
| 553 |
boundary |
| 554 |
or getattr(first_enum, '_boundary_', None) |
| 555 |
) |
| 556 |
classdict['_flag_mask_'] = 0 |
| 557 |
classdict['_singles_mask_'] = 0 |
| 558 |
classdict['_all_bits_'] = 0 |
| 559 |
classdict['_inverted_'] = None |
| 560 |
try: |
| 561 |
exc = None |
| 562 |
enum_class = super().__new__(metacls, cls, bases, classdict, **kwds) |
| 563 |
except RuntimeError as e: |
| 564 |
|
| 565 |
|
| 566 |
exc = e.__cause__ or e |
| 567 |
if exc is not None: |
| 568 |
raise exc |
| 569 |
|
| 570 |
|
| 571 |
classdict.update(enum_class.__dict__) |
| 572 |
|
| 573 |
|
| 574 |
|
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
|
| 579 |
if ReprEnum is not None and ReprEnum in bases: |
| 580 |
if member_type is object: |
| 581 |
raise TypeError( |
| 582 |
'ReprEnum subclasses must be mixed with a data type (i.e.' |
| 583 |
' int, str, float, etc.)' |
| 584 |
) |
| 585 |
if '__format__' not in classdict: |
| 586 |
enum_class.__format__ = member_type.__format__ |
| 587 |
classdict['__format__'] = enum_class.__format__ |
| 588 |
if '__str__' not in classdict: |
| 589 |
method = member_type.__str__ |
| 590 |
if method is object.__str__: |
| 591 |
|
| 592 |
|
| 593 |
method = member_type.__repr__ |
| 594 |
enum_class.__str__ = method |
| 595 |
classdict['__str__'] = enum_class.__str__ |
| 596 |
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): |
| 597 |
if name not in classdict: |
| 598 |
|
| 599 |
enum_method = getattr(first_enum, name) |
| 600 |
found_method = getattr(enum_class, name) |
| 601 |
object_method = getattr(object, name) |
| 602 |
data_type_method = getattr(member_type, name) |
| 603 |
if found_method in (data_type_method, object_method): |
| 604 |
setattr(enum_class, name, enum_method) |
| 605 |
|
| 606 |
|
| 607 |
if Flag is not None and issubclass(enum_class, Flag): |
| 608 |
for name in ( |
| 609 |
'__or__', '__and__', '__xor__', |
| 610 |
'__ror__', '__rand__', '__rxor__', |
| 611 |
'__invert__' |
| 612 |
): |
| 613 |
if name not in classdict: |
| 614 |
enum_method = getattr(Flag, name) |
| 615 |
setattr(enum_class, name, enum_method) |
| 616 |
classdict[name] = enum_method |
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
if Enum is not None: |
| 621 |
|
| 622 |
|
| 623 |
if save_new: |
| 624 |
enum_class.__new_member__ = __new__ |
| 625 |
enum_class.__new__ = Enum.__new__ |
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
|
| 636 |
if _order_ is not None: |
| 637 |
if isinstance(_order_, str): |
| 638 |
_order_ = _order_.replace(',', ' ').split() |
| 639 |
|
| 640 |
|
| 641 |
if ( |
| 642 |
Flag is None and cls != 'Flag' |
| 643 |
or Flag is not None and not issubclass(enum_class, Flag) |
| 644 |
): |
| 645 |
delattr(enum_class, '_boundary_') |
| 646 |
delattr(enum_class, '_flag_mask_') |
| 647 |
delattr(enum_class, '_singles_mask_') |
| 648 |
delattr(enum_class, '_all_bits_') |
| 649 |
delattr(enum_class, '_inverted_') |
| 650 |
elif Flag is not None and issubclass(enum_class, Flag): |
| 651 |
|
| 652 |
member_list = [m._value_ for m in enum_class] |
| 653 |
if member_list != sorted(member_list): |
| 654 |
enum_class._iter_member_ = enum_class._iter_member_by_def_ |
| 655 |
if _order_: |
| 656 |
|
| 657 |
_order_ = [ |
| 658 |
o |
| 659 |
for o in _order_ |
| 660 |
if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_) |
| 661 |
] |
| 662 |
|
| 663 |
if _order_: |
| 664 |
|
| 665 |
_order_ = [ |
| 666 |
o |
| 667 |
for o in _order_ |
| 668 |
if ( |
| 669 |
o not in enum_class._member_map_ |
| 670 |
or |
| 671 |
(o in enum_class._member_map_ and o in enum_class._member_names_) |
| 672 |
)] |
| 673 |
|
| 674 |
if _order_ != enum_class._member_names_: |
| 675 |
raise TypeError( |
| 676 |
'member order does not match _order_:\n %r\n %r' |
| 677 |
% (enum_class._member_names_, _order_) |
| 678 |
) |
| 679 |
|
| 680 |
return enum_class |
| 681 |
|
| 682 |
def __bool__(cls): |
| 683 |
""" |
| 684 |
classes/types should always be True. |
| 685 |
""" |
| 686 |
return True |
| 687 |
|
| 688 |
def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None): |
| 689 |
""" |
| 690 |
Either returns an existing member, or creates a new enum class. |
| 691 |
|
| 692 |
This method is used both when an enum class is given a value to match |
| 693 |
to an enumeration member (i.e. Color(3)) and for the functional API |
| 694 |
(i.e. Color = Enum('Color', names='RED GREEN BLUE')). |
| 695 |
|
| 696 |
When used for the functional API: |
| 697 |
|
| 698 |
`value` will be the name of the new class. |
| 699 |
|
| 700 |
`names` should be either a string of white-space/comma delimited names |
| 701 |
(values will start at `start`), or an iterator/mapping of name, value pairs. |
| 702 |
|
| 703 |
`module` should be set to the module this class is being created in; |
| 704 |
if it is not set, an attempt to find that module will be made, but if |
| 705 |
it fails the class will not be picklable. |
| 706 |
|
| 707 |
`qualname` should be set to the actual location this class can be found |
| 708 |
at in its module; by default it is set to the global scope. If this is |
| 709 |
not correct, unpickling will fail in some circumstances. |
| 710 |
|
| 711 |
`type`, if set, will be mixed in as the first base class. |
| 712 |
""" |
| 713 |
if names is None: |
| 714 |
return cls.__new__(cls, value) |
| 715 |
|
| 716 |
return cls._create_( |
| 717 |
value, |
| 718 |
names, |
| 719 |
module=module, |
| 720 |
qualname=qualname, |
| 721 |
type=type, |
| 722 |
start=start, |
| 723 |
boundary=boundary, |
| 724 |
) |
| 725 |
|
| 726 |
def __contains__(cls, member): |
| 727 |
""" |
| 728 |
Return True if member is a member of this enum |
| 729 |
raises TypeError if member is not an enum member |
| 730 |
|
| 731 |
note: in 3.12 TypeError will no longer be raised, and True will also be |
| 732 |
returned if member is the value of a member in this enum |
| 733 |
""" |
| 734 |
if not isinstance(member, Enum): |
| 735 |
import warnings |
| 736 |
warnings.warn( |
| 737 |
"in 3.12 __contains__ will no longer raise TypeError, but will return True or\n" |
| 738 |
"False depending on whether the value is a member or the value of a member", |
| 739 |
DeprecationWarning, |
| 740 |
stacklevel=2, |
| 741 |
) |
| 742 |
raise TypeError( |
| 743 |
"unsupported operand type(s) for 'in': '%s' and '%s'" % ( |
| 744 |
type(member).__qualname__, cls.__class__.__qualname__)) |
| 745 |
return isinstance(member, cls) and member._name_ in cls._member_map_ |
| 746 |
|
| 747 |
def __delattr__(cls, attr): |
| 748 |
|
| 749 |
|
| 750 |
if attr in cls._member_map_: |
| 751 |
raise AttributeError("%r cannot delete member %r." % (cls.__name__, attr)) |
| 752 |
super().__delattr__(attr) |
| 753 |
|
| 754 |
def __dir__(cls): |
| 755 |
interesting = set([ |
| 756 |
'__class__', '__contains__', '__doc__', '__getitem__', |
| 757 |
'__iter__', '__len__', '__members__', '__module__', |
| 758 |
'__name__', '__qualname__', |
| 759 |
] |
| 760 |
+ cls._member_names_ |
| 761 |
) |
| 762 |
if cls._new_member_ is not object.__new__: |
| 763 |
interesting.add('__new__') |
| 764 |
if cls.__init_subclass__ is not object.__init_subclass__: |
| 765 |
interesting.add('__init_subclass__') |
| 766 |
if cls._member_type_ is object: |
| 767 |
return sorted(interesting) |
| 768 |
else: |
| 769 |
|
| 770 |
return sorted(set(dir(cls._member_type_)) | interesting) |
| 771 |
|
| 772 |
def __getattr__(cls, name): |
| 773 |
""" |
| 774 |
Return the enum member matching `name` |
| 775 |
|
| 776 |
We use __getattr__ instead of descriptors or inserting into the enum |
| 777 |
class' __dict__ in order to support `name` and `value` being both |
| 778 |
properties for enum members (which live in the class' __dict__) and |
| 779 |
enum members themselves. |
| 780 |
""" |
| 781 |
if _is_dunder(name): |
| 782 |
raise AttributeError(name) |
| 783 |
try: |
| 784 |
return cls._member_map_[name] |
| 785 |
except KeyError: |
| 786 |
raise AttributeError(name) from None |
| 787 |
|
| 788 |
def __getitem__(cls, name): |
| 789 |
""" |
| 790 |
Return the member matching `name`. |
| 791 |
""" |
| 792 |
return cls._member_map_[name] |
| 793 |
|
| 794 |
def __iter__(cls): |
| 795 |
""" |
| 796 |
Return members in definition order. |
| 797 |
""" |
| 798 |
return (cls._member_map_[name] for name in cls._member_names_) |
| 799 |
|
| 800 |
def __len__(cls): |
| 801 |
""" |
| 802 |
Return the number of members (no aliases) |
| 803 |
""" |
| 804 |
return len(cls._member_names_) |
| 805 |
|
| 806 |
@bltns.property |
| 807 |
def __members__(cls): |
| 808 |
""" |
| 809 |
Returns a mapping of member name->value. |
| 810 |
|
| 811 |
This mapping lists all enum members, including aliases. Note that this |
| 812 |
is a read-only view of the internal mapping. |
| 813 |
""" |
| 814 |
return MappingProxyType(cls._member_map_) |
| 815 |
|
| 816 |
def __repr__(cls): |
| 817 |
if Flag is not None and issubclass(cls, Flag): |
| 818 |
return "<flag %r>" % cls.__name__ |
| 819 |
else: |
| 820 |
return "<enum %r>" % cls.__name__ |
| 821 |
|
| 822 |
def __reversed__(cls): |
| 823 |
""" |
| 824 |
Return members in reverse definition order. |
| 825 |
""" |
| 826 |
return (cls._member_map_[name] for name in reversed(cls._member_names_)) |
| 827 |
|
| 828 |
def __setattr__(cls, name, value): |
| 829 |
""" |
| 830 |
Block attempts to reassign Enum members. |
| 831 |
|
| 832 |
A simple assignment to the class namespace only changes one of the |
| 833 |
several possible ways to get an Enum member from the Enum class, |
| 834 |
resulting in an inconsistent Enumeration. |
| 835 |
""" |
| 836 |
member_map = cls.__dict__.get('_member_map_', {}) |
| 837 |
if name in member_map: |
| 838 |
raise AttributeError('cannot reassign member %r' % (name, )) |
| 839 |
super().__setattr__(name, value) |
| 840 |
|
| 841 |
def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1, boundary=None): |
| 842 |
""" |
| 843 |
Convenience method to create a new Enum class. |
| 844 |
|
| 845 |
`names` can be: |
| 846 |
|
| 847 |
* A string containing member names, separated either with spaces or |
| 848 |
commas. Values are incremented by 1 from `start`. |
| 849 |
* An iterable of member names. Values are incremented by 1 from `start`. |
| 850 |
* An iterable of (member name, value) pairs. |
| 851 |
* A mapping of member name -> value pairs. |
| 852 |
""" |
| 853 |
metacls = cls.__class__ |
| 854 |
bases = (cls, ) if type is None else (type, cls) |
| 855 |
_, first_enum = cls._get_mixins_(class_name, bases) |
| 856 |
classdict = metacls.__prepare__(class_name, bases) |
| 857 |
|
| 858 |
|
| 859 |
if isinstance(names, str): |
| 860 |
names = names.replace(',', ' ').split() |
| 861 |
if isinstance(names, (tuple, list)) and names and isinstance(names[0], str): |
| 862 |
original_names, names = names, [] |
| 863 |
last_values = [] |
| 864 |
for count, name in enumerate(original_names): |
| 865 |
value = first_enum._generate_next_value_(name, start, count, last_values[:]) |
| 866 |
last_values.append(value) |
| 867 |
names.append((name, value)) |
| 868 |
if names is None: |
| 869 |
names = () |
| 870 |
|
| 871 |
|
| 872 |
for item in names: |
| 873 |
if isinstance(item, str): |
| 874 |
member_name, member_value = item, names[item] |
| 875 |
else: |
| 876 |
member_name, member_value = item |
| 877 |
classdict[member_name] = member_value |
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
if module is None: |
| 882 |
try: |
| 883 |
module = sys._getframe(2).f_globals['__name__'] |
| 884 |
except (AttributeError, ValueError, KeyError): |
| 885 |
pass |
| 886 |
if module is None: |
| 887 |
_make_class_unpicklable(classdict) |
| 888 |
else: |
| 889 |
classdict['__module__'] = module |
| 890 |
if qualname is not None: |
| 891 |
classdict['__qualname__'] = qualname |
| 892 |
|
| 893 |
return metacls.__new__(metacls, class_name, bases, classdict, boundary=boundary) |
| 894 |
|
| 895 |
def _convert_(cls, name, module, filter, source=None, *, boundary=None, as_global=False): |
| 896 |
""" |
| 897 |
Create a new Enum subclass that replaces a collection of global constants |
| 898 |
""" |
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
module_globals = sys.modules[module].__dict__ |
| 905 |
if source: |
| 906 |
source = source.__dict__ |
| 907 |
else: |
| 908 |
source = module_globals |
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
members = [ |
| 913 |
(name, value) |
| 914 |
for name, value in source.items() |
| 915 |
if filter(name)] |
| 916 |
try: |
| 917 |
|
| 918 |
members.sort(key=lambda t: (t[1], t[0])) |
| 919 |
except TypeError: |
| 920 |
|
| 921 |
members.sort(key=lambda t: t[0]) |
| 922 |
body = {t[0]: t[1] for t in members} |
| 923 |
body['__module__'] = module |
| 924 |
tmp_cls = type(name, (object, ), body) |
| 925 |
cls = _simple_enum(etype=cls, boundary=boundary or KEEP)(tmp_cls) |
| 926 |
if as_global: |
| 927 |
global_enum(cls) |
| 928 |
else: |
| 929 |
sys.modules[cls.__module__].__dict__.update(cls.__members__) |
| 930 |
module_globals[name] = cls |
| 931 |
return cls |
| 932 |
|
| 933 |
@classmethod |
| 934 |
def _check_for_existing_members_(mcls, class_name, bases): |
| 935 |
for chain in bases: |
| 936 |
for base in chain.__mro__: |
| 937 |
if isinstance(base, EnumType) and base._member_names_: |
| 938 |
raise TypeError( |
| 939 |
"<enum %r> cannot extend %r" |
| 940 |
% (class_name, base) |
| 941 |
) |
| 942 |
|
| 943 |
@classmethod |
| 944 |
def _get_mixins_(mcls, class_name, bases): |
| 945 |
""" |
| 946 |
Returns the type for creating enum members, and the first inherited |
| 947 |
enum class. |
| 948 |
|
| 949 |
bases: the tuple of bases that was given to __new__ |
| 950 |
""" |
| 951 |
if not bases: |
| 952 |
return object, Enum |
| 953 |
|
| 954 |
mcls._check_for_existing_members_(class_name, bases) |
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
first_enum = bases[-1] |
| 959 |
if not isinstance(first_enum, EnumType): |
| 960 |
raise TypeError("new enumerations should be created as " |
| 961 |
"`EnumName([mixin_type, ...] [data_type,] enum_type)`") |
| 962 |
member_type = mcls._find_data_type_(class_name, bases) or object |
| 963 |
return member_type, first_enum |
| 964 |
|
| 965 |
@classmethod |
| 966 |
def _find_data_repr_(mcls, class_name, bases): |
| 967 |
for chain in bases: |
| 968 |
for base in chain.__mro__: |
| 969 |
if base is object: |
| 970 |
continue |
| 971 |
elif isinstance(base, EnumType): |
| 972 |
|
| 973 |
return base._value_repr_ |
| 974 |
elif '__repr__' in base.__dict__: |
| 975 |
|
| 976 |
return base.__dict__['__repr__'] |
| 977 |
return None |
| 978 |
|
| 979 |
@classmethod |
| 980 |
def _find_data_type_(mcls, class_name, bases): |
| 981 |
|
| 982 |
data_types = set() |
| 983 |
base_chain = set() |
| 984 |
for chain in bases: |
| 985 |
candidate = None |
| 986 |
for base in chain.__mro__: |
| 987 |
base_chain.add(base) |
| 988 |
if base is object: |
| 989 |
continue |
| 990 |
elif isinstance(base, EnumType): |
| 991 |
if base._member_type_ is not object: |
| 992 |
data_types.add(base._member_type_) |
| 993 |
break |
| 994 |
elif '__new__' in base.__dict__ or '__dataclass_fields__' in base.__dict__: |
| 995 |
if isinstance(base, EnumType): |
| 996 |
continue |
| 997 |
data_types.add(candidate or base) |
| 998 |
break |
| 999 |
else: |
| 1000 |
candidate = candidate or base |
| 1001 |
if len(data_types) > 1: |
| 1002 |
raise TypeError('too many data types for %r: %r' % (class_name, data_types)) |
| 1003 |
elif data_types: |
| 1004 |
return data_types.pop() |
| 1005 |
else: |
| 1006 |
return None |
| 1007 |
|
| 1008 |
@classmethod |
| 1009 |
def _find_new_(mcls, classdict, member_type, first_enum): |
| 1010 |
""" |
| 1011 |
Returns the __new__ to be used for creating the enum members. |
| 1012 |
|
| 1013 |
classdict: the class dictionary given to __new__ |
| 1014 |
member_type: the data type whose __new__ will be used by default |
| 1015 |
first_enum: enumeration to check for an overriding __new__ |
| 1016 |
""" |
| 1017 |
|
| 1018 |
|
| 1019 |
|
| 1020 |
__new__ = classdict.get('__new__', None) |
| 1021 |
|
| 1022 |
|
| 1023 |
save_new = first_enum is not None and __new__ is not None |
| 1024 |
|
| 1025 |
if __new__ is None: |
| 1026 |
|
| 1027 |
|
| 1028 |
for method in ('__new_member__', '__new__'): |
| 1029 |
for possible in (member_type, first_enum): |
| 1030 |
target = getattr(possible, method, None) |
| 1031 |
if target not in { |
| 1032 |
None, |
| 1033 |
None.__new__, |
| 1034 |
object.__new__, |
| 1035 |
Enum.__new__, |
| 1036 |
}: |
| 1037 |
__new__ = target |
| 1038 |
break |
| 1039 |
if __new__ is not None: |
| 1040 |
break |
| 1041 |
else: |
| 1042 |
__new__ = object.__new__ |
| 1043 |
|
| 1044 |
|
| 1045 |
|
| 1046 |
|
| 1047 |
if first_enum is None or __new__ in (Enum.__new__, object.__new__): |
| 1048 |
use_args = False |
| 1049 |
else: |
| 1050 |
use_args = True |
| 1051 |
return __new__, save_new, use_args |
| 1052 |
EnumMeta = EnumType |
| 1053 |
|
| 1054 |
|
| 1055 |
class Enum(metaclass=EnumType): |
| 1056 |
""" |
| 1057 |
Create a collection of name/value pairs. |
| 1058 |
|
| 1059 |
Example enumeration: |
| 1060 |
|
| 1061 |
>>> class Color(Enum): |
| 1062 |
... RED = 1 |
| 1063 |
... BLUE = 2 |
| 1064 |
... GREEN = 3 |
| 1065 |
|
| 1066 |
Access them by: |
| 1067 |
|
| 1068 |
- attribute access:: |
| 1069 |
|
| 1070 |
>>> Color.RED |
| 1071 |
<Color.RED: 1> |
| 1072 |
|
| 1073 |
- value lookup: |
| 1074 |
|
| 1075 |
>>> Color(1) |
| 1076 |
<Color.RED: 1> |
| 1077 |
|
| 1078 |
- name lookup: |
| 1079 |
|
| 1080 |
>>> Color['RED'] |
| 1081 |
<Color.RED: 1> |
| 1082 |
|
| 1083 |
Enumerations can be iterated over, and know how many members they have: |
| 1084 |
|
| 1085 |
>>> len(Color) |
| 1086 |
3 |
| 1087 |
|
| 1088 |
>>> list(Color) |
| 1089 |
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>] |
| 1090 |
|
| 1091 |
Methods can be added to enumerations, and members can have their own |
| 1092 |
attributes -- see the documentation for details. |
| 1093 |
""" |
| 1094 |
|
| 1095 |
def __new__(cls, value): |
| 1096 |
|
| 1097 |
|
| 1098 |
|
| 1099 |
if type(value) is cls: |
| 1100 |
|
| 1101 |
return value |
| 1102 |
|
| 1103 |
|
| 1104 |
try: |
| 1105 |
return cls._value2member_map_[value] |
| 1106 |
except KeyError: |
| 1107 |
|
| 1108 |
pass |
| 1109 |
except TypeError: |
| 1110 |
|
| 1111 |
for member in cls._member_map_.values(): |
| 1112 |
if member._value_ == value: |
| 1113 |
return member |
| 1114 |
|
| 1115 |
|
| 1116 |
if not cls._member_map_: |
| 1117 |
raise TypeError("%r has no members defined" % cls) |
| 1118 |
|
| 1119 |
|
| 1120 |
try: |
| 1121 |
exc = None |
| 1122 |
result = cls._missing_(value) |
| 1123 |
except Exception as e: |
| 1124 |
exc = e |
| 1125 |
result = None |
| 1126 |
try: |
| 1127 |
if isinstance(result, cls): |
| 1128 |
return result |
| 1129 |
elif ( |
| 1130 |
Flag is not None and issubclass(cls, Flag) |
| 1131 |
and cls._boundary_ is EJECT and isinstance(result, int) |
| 1132 |
): |
| 1133 |
return result |
| 1134 |
else: |
| 1135 |
ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__)) |
| 1136 |
if result is None and exc is None: |
| 1137 |
raise ve_exc |
| 1138 |
elif exc is None: |
| 1139 |
exc = TypeError( |
| 1140 |
'error in %s._missing_: returned %r instead of None or a valid member' |
| 1141 |
% (cls.__name__, result) |
| 1142 |
) |
| 1143 |
if not isinstance(exc, ValueError): |
| 1144 |
exc.__context__ = ve_exc |
| 1145 |
raise exc |
| 1146 |
finally: |
| 1147 |
|
| 1148 |
exc = None |
| 1149 |
ve_exc = None |
| 1150 |
|
| 1151 |
def __init__(self, *args, **kwds): |
| 1152 |
pass |
| 1153 |
|
| 1154 |
def _generate_next_value_(name, start, count, last_values): |
| 1155 |
""" |
| 1156 |
Generate the next value when not given. |
| 1157 |
|
| 1158 |
name: the name of the member |
| 1159 |
start: the initial start value or None |
| 1160 |
count: the number of existing members |
| 1161 |
last_values: the list of values assigned |
| 1162 |
""" |
| 1163 |
if not last_values: |
| 1164 |
return start |
| 1165 |
try: |
| 1166 |
last = last_values[-1] |
| 1167 |
last_values.sort() |
| 1168 |
if last == last_values[-1]: |
| 1169 |
|
| 1170 |
return last + 1 |
| 1171 |
else: |
| 1172 |
|
| 1173 |
raise TypeError |
| 1174 |
except TypeError: |
| 1175 |
import warnings |
| 1176 |
warnings.warn( |
| 1177 |
"In 3.13 the default `auto()`/`_generate_next_value_` will require all values to be sortable and support adding +1\n" |
| 1178 |
"and the value returned will be the largest value in the enum incremented by 1", |
| 1179 |
DeprecationWarning, |
| 1180 |
stacklevel=3, |
| 1181 |
) |
| 1182 |
for v in reversed(last_values): |
| 1183 |
try: |
| 1184 |
return v + 1 |
| 1185 |
except TypeError: |
| 1186 |
pass |
| 1187 |
return start |
| 1188 |
|
| 1189 |
@classmethod |
| 1190 |
def _missing_(cls, value): |
| 1191 |
return None |
| 1192 |
|
| 1193 |
def __repr__(self): |
| 1194 |
v_repr = self.__class__._value_repr_ or repr |
| 1195 |
return "<%s.%s: %s>" % (self.__class__.__name__, self._name_, v_repr(self._value_)) |
| 1196 |
|
| 1197 |
def __str__(self): |
| 1198 |
return "%s.%s" % (self.__class__.__name__, self._name_, ) |
| 1199 |
|
| 1200 |
def __dir__(self): |
| 1201 |
""" |
| 1202 |
Returns public methods and other interesting attributes. |
| 1203 |
""" |
| 1204 |
interesting = set() |
| 1205 |
if self.__class__._member_type_ is not object: |
| 1206 |
interesting = set(object.__dir__(self)) |
| 1207 |
for name in getattr(self, '__dict__', []): |
| 1208 |
if name[0] != '_' and name not in self._member_map_: |
| 1209 |
interesting.add(name) |
| 1210 |
for cls in self.__class__.mro(): |
| 1211 |
for name, obj in cls.__dict__.items(): |
| 1212 |
if name[0] == '_': |
| 1213 |
continue |
| 1214 |
if isinstance(obj, property): |
| 1215 |
|
| 1216 |
if obj.fget is not None or name not in self._member_map_: |
| 1217 |
interesting.add(name) |
| 1218 |
else: |
| 1219 |
|
| 1220 |
interesting.discard(name) |
| 1221 |
elif name not in self._member_map_: |
| 1222 |
interesting.add(name) |
| 1223 |
names = sorted( |
| 1224 |
set(['__class__', '__doc__', '__eq__', '__hash__', '__module__']) |
| 1225 |
| interesting |
| 1226 |
) |
| 1227 |
return names |
| 1228 |
|
| 1229 |
def __format__(self, format_spec): |
| 1230 |
return str.__format__(str(self), format_spec) |
| 1231 |
|
| 1232 |
def __hash__(self): |
| 1233 |
return hash(self._name_) |
| 1234 |
|
| 1235 |
def __reduce_ex__(self, proto): |
| 1236 |
return self.__class__, (self._value_, ) |
| 1237 |
|
| 1238 |
def __deepcopy__(self,memo): |
| 1239 |
return self |
| 1240 |
|
| 1241 |
def __copy__(self): |
| 1242 |
return self |
| 1243 |
|
| 1244 |
|
| 1245 |
|
| 1246 |
|
| 1247 |
|
| 1248 |
|
| 1249 |
|
| 1250 |
|
| 1251 |
|
| 1252 |
@property |
| 1253 |
def name(self): |
| 1254 |
"""The name of the Enum member.""" |
| 1255 |
return self._name_ |
| 1256 |
|
| 1257 |
@property |
| 1258 |
def value(self): |
| 1259 |
"""The value of the Enum member.""" |
| 1260 |
return self._value_ |
| 1261 |
|
| 1262 |
|
| 1263 |
class ReprEnum(Enum): |
| 1264 |
""" |
| 1265 |
Only changes the repr(), leaving str() and format() to the mixed-in type. |
| 1266 |
""" |
| 1267 |
|
| 1268 |
|
| 1269 |
class IntEnum(int, ReprEnum): |
| 1270 |
""" |
| 1271 |
Enum where members are also (and must be) ints |
| 1272 |
""" |
| 1273 |
|
| 1274 |
|
| 1275 |
class StrEnum(str, ReprEnum): |
| 1276 |
""" |
| 1277 |
Enum where members are also (and must be) strings |
| 1278 |
""" |
| 1279 |
|
| 1280 |
def __new__(cls, *values): |
| 1281 |
"values must already be of type `str`" |
| 1282 |
if len(values) > 3: |
| 1283 |
raise TypeError('too many arguments for str(): %r' % (values, )) |
| 1284 |
if len(values) == 1: |
| 1285 |
|
| 1286 |
if not isinstance(values[0], str): |
| 1287 |
raise TypeError('%r is not a string' % (values[0], )) |
| 1288 |
if len(values) >= 2: |
| 1289 |
|
| 1290 |
if not isinstance(values[1], str): |
| 1291 |
raise TypeError('encoding must be a string, not %r' % (values[1], )) |
| 1292 |
if len(values) == 3: |
| 1293 |
|
| 1294 |
if not isinstance(values[2], str): |
| 1295 |
raise TypeError('errors must be a string, not %r' % (values[2])) |
| 1296 |
value = str(*values) |
| 1297 |
member = str.__new__(cls, value) |
| 1298 |
member._value_ = value |
| 1299 |
return member |
| 1300 |
|
| 1301 |
def _generate_next_value_(name, start, count, last_values): |
| 1302 |
""" |
| 1303 |
Return the lower-cased version of the member name. |
| 1304 |
""" |
| 1305 |
return name.lower() |
| 1306 |
|
| 1307 |
|
| 1308 |
def pickle_by_global_name(self, proto): |
| 1309 |
|
| 1310 |
return self.name |
| 1311 |
_reduce_ex_by_global_name = pickle_by_global_name |
| 1312 |
|
| 1313 |
def pickle_by_enum_name(self, proto): |
| 1314 |
|
| 1315 |
return getattr, (self.__class__, self._name_) |
| 1316 |
|
| 1317 |
class FlagBoundary(StrEnum): |
| 1318 |
""" |
| 1319 |
control how out of range values are handled |
| 1320 |
"strict" -> error is raised [default for Flag] |
| 1321 |
"conform" -> extra bits are discarded |
| 1322 |
"eject" -> lose flag status |
| 1323 |
"keep" -> keep flag status and all bits [default for IntFlag] |
| 1324 |
""" |
| 1325 |
STRICT = auto() |
| 1326 |
CONFORM = auto() |
| 1327 |
EJECT = auto() |
| 1328 |
KEEP = auto() |
| 1329 |
STRICT, CONFORM, EJECT, KEEP = FlagBoundary |
| 1330 |
|
| 1331 |
|
| 1332 |
class Flag(Enum, boundary=STRICT): |
| 1333 |
""" |
| 1334 |
Support for flags |
| 1335 |
""" |
| 1336 |
|
| 1337 |
_numeric_repr_ = repr |
| 1338 |
|
| 1339 |
def _generate_next_value_(name, start, count, last_values): |
| 1340 |
""" |
| 1341 |
Generate the next value when not given. |
| 1342 |
|
| 1343 |
name: the name of the member |
| 1344 |
start: the initial start value or None |
| 1345 |
count: the number of existing members |
| 1346 |
last_values: the last value assigned or None |
| 1347 |
""" |
| 1348 |
if not count: |
| 1349 |
return start if start is not None else 1 |
| 1350 |
last_value = max(last_values) |
| 1351 |
try: |
| 1352 |
high_bit = _high_bit(last_value) |
| 1353 |
except Exception: |
| 1354 |
raise TypeError('invalid flag value %r' % last_value) from None |
| 1355 |
return 2 ** (high_bit+1) |
| 1356 |
|
| 1357 |
@classmethod |
| 1358 |
def _iter_member_by_value_(cls, value): |
| 1359 |
""" |
| 1360 |
Extract all members from the value in definition (i.e. increasing value) order. |
| 1361 |
""" |
| 1362 |
for val in _iter_bits_lsb(value & cls._flag_mask_): |
| 1363 |
yield cls._value2member_map_.get(val) |
| 1364 |
|
| 1365 |
_iter_member_ = _iter_member_by_value_ |
| 1366 |
|
| 1367 |
@classmethod |
| 1368 |
def _iter_member_by_def_(cls, value): |
| 1369 |
""" |
| 1370 |
Extract all members from the value in definition order. |
| 1371 |
""" |
| 1372 |
yield from sorted( |
| 1373 |
cls._iter_member_by_value_(value), |
| 1374 |
key=lambda m: m._sort_order_, |
| 1375 |
) |
| 1376 |
|
| 1377 |
@classmethod |
| 1378 |
def _missing_(cls, value): |
| 1379 |
""" |
| 1380 |
Create a composite member containing all canonical members present in `value`. |
| 1381 |
|
| 1382 |
If non-member values are present, result depends on `_boundary_` setting. |
| 1383 |
""" |
| 1384 |
if not isinstance(value, int): |
| 1385 |
raise ValueError( |
| 1386 |
"%r is not a valid %s" % (value, cls.__qualname__) |
| 1387 |
) |
| 1388 |
|
| 1389 |
|
| 1390 |
|
| 1391 |
|
| 1392 |
flag_mask = cls._flag_mask_ |
| 1393 |
singles_mask = cls._singles_mask_ |
| 1394 |
all_bits = cls._all_bits_ |
| 1395 |
neg_value = None |
| 1396 |
if ( |
| 1397 |
not ~all_bits <= value <= all_bits |
| 1398 |
or value & (all_bits ^ flag_mask) |
| 1399 |
): |
| 1400 |
if cls._boundary_ is STRICT: |
| 1401 |
max_bits = max(value.bit_length(), flag_mask.bit_length()) |
| 1402 |
raise ValueError( |
| 1403 |
"%r invalid value %r\n given %s\n allowed %s" % ( |
| 1404 |
cls, value, bin(value, max_bits), bin(flag_mask, max_bits), |
| 1405 |
)) |
| 1406 |
elif cls._boundary_ is CONFORM: |
| 1407 |
value = value & flag_mask |
| 1408 |
elif cls._boundary_ is EJECT: |
| 1409 |
return value |
| 1410 |
elif cls._boundary_ is KEEP: |
| 1411 |
if value < 0: |
| 1412 |
value = ( |
| 1413 |
max(all_bits+1, 2**(value.bit_length())) |
| 1414 |
+ value |
| 1415 |
) |
| 1416 |
else: |
| 1417 |
raise ValueError( |
| 1418 |
'%r unknown flag boundary %r' % (cls, cls._boundary_, ) |
| 1419 |
) |
| 1420 |
if value < 0: |
| 1421 |
neg_value = value |
| 1422 |
value = all_bits + 1 + value |
| 1423 |
|
| 1424 |
unknown = value & ~flag_mask |
| 1425 |
aliases = value & ~singles_mask |
| 1426 |
member_value = value & singles_mask |
| 1427 |
if unknown and cls._boundary_ is not KEEP: |
| 1428 |
raise ValueError( |
| 1429 |
'%s(%r) --> unknown values %r [%s]' |
| 1430 |
% (cls.__name__, value, unknown, bin(unknown)) |
| 1431 |
) |
| 1432 |
|
| 1433 |
if cls._member_type_ is object: |
| 1434 |
|
| 1435 |
pseudo_member = object.__new__(cls) |
| 1436 |
else: |
| 1437 |
pseudo_member = cls._member_type_.__new__(cls, value) |
| 1438 |
if not hasattr(pseudo_member, '_value_'): |
| 1439 |
pseudo_member._value_ = value |
| 1440 |
if member_value or aliases: |
| 1441 |
members = [] |
| 1442 |
combined_value = 0 |
| 1443 |
for m in cls._iter_member_(member_value): |
| 1444 |
members.append(m) |
| 1445 |
combined_value |= m._value_ |
| 1446 |
if aliases: |
| 1447 |
value = member_value | aliases |
| 1448 |
for n, pm in cls._member_map_.items(): |
| 1449 |
if pm not in members and pm._value_ and pm._value_ & value == pm._value_: |
| 1450 |
members.append(pm) |
| 1451 |
combined_value |= pm._value_ |
| 1452 |
unknown = value ^ combined_value |
| 1453 |
pseudo_member._name_ = '|'.join([m._name_ for m in members]) |
| 1454 |
if not combined_value: |
| 1455 |
pseudo_member._name_ = None |
| 1456 |
elif unknown and cls._boundary_ is STRICT: |
| 1457 |
raise ValueError('%r: no members with value %r' % (cls, unknown)) |
| 1458 |
elif unknown: |
| 1459 |
pseudo_member._name_ += '|%s' % cls._numeric_repr_(unknown) |
| 1460 |
else: |
| 1461 |
pseudo_member._name_ = None |
| 1462 |
|
| 1463 |
|
| 1464 |
|
| 1465 |
pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member) |
| 1466 |
if neg_value is not None: |
| 1467 |
cls._value2member_map_[neg_value] = pseudo_member |
| 1468 |
return pseudo_member |
| 1469 |
|
| 1470 |
def __contains__(self, other): |
| 1471 |
""" |
| 1472 |
Returns True if self has at least the same flags set as other. |
| 1473 |
""" |
| 1474 |
if not isinstance(other, self.__class__): |
| 1475 |
raise TypeError( |
| 1476 |
"unsupported operand type(s) for 'in': %r and %r" % ( |
| 1477 |
type(other).__qualname__, self.__class__.__qualname__)) |
| 1478 |
return other._value_ & self._value_ == other._value_ |
| 1479 |
|
| 1480 |
def __iter__(self): |
| 1481 |
""" |
| 1482 |
Returns flags in definition order. |
| 1483 |
""" |
| 1484 |
yield from self._iter_member_(self._value_) |
| 1485 |
|
| 1486 |
def __len__(self): |
| 1487 |
return self._value_.bit_count() |
| 1488 |
|
| 1489 |
def __repr__(self): |
| 1490 |
cls_name = self.__class__.__name__ |
| 1491 |
v_repr = self.__class__._value_repr_ or repr |
| 1492 |
if self._name_ is None: |
| 1493 |
return "<%s: %s>" % (cls_name, v_repr(self._value_)) |
| 1494 |
else: |
| 1495 |
return "<%s.%s: %s>" % (cls_name, self._name_, v_repr(self._value_)) |
| 1496 |
|
| 1497 |
def __str__(self): |
| 1498 |
cls_name = self.__class__.__name__ |
| 1499 |
if self._name_ is None: |
| 1500 |
return '%s(%r)' % (cls_name, self._value_) |
| 1501 |
else: |
| 1502 |
return "%s.%s" % (cls_name, self._name_) |
| 1503 |
|
| 1504 |
def __bool__(self): |
| 1505 |
return bool(self._value_) |
| 1506 |
|
| 1507 |
def _get_value(self, flag): |
| 1508 |
if isinstance(flag, self.__class__): |
| 1509 |
return flag._value_ |
| 1510 |
elif self._member_type_ is not object and isinstance(flag, self._member_type_): |
| 1511 |
return flag |
| 1512 |
return NotImplemented |
| 1513 |
|
| 1514 |
def __or__(self, other): |
| 1515 |
other_value = self._get_value(other) |
| 1516 |
if other_value is NotImplemented: |
| 1517 |
return NotImplemented |
| 1518 |
|
| 1519 |
for flag in self, other: |
| 1520 |
if self._get_value(flag) is None: |
| 1521 |
raise TypeError(f"'{flag}' cannot be combined with other flags with |") |
| 1522 |
value = self._value_ |
| 1523 |
return self.__class__(value | other_value) |
| 1524 |
|
| 1525 |
def __and__(self, other): |
| 1526 |
other_value = self._get_value(other) |
| 1527 |
if other_value is NotImplemented: |
| 1528 |
return NotImplemented |
| 1529 |
|
| 1530 |
for flag in self, other: |
| 1531 |
if self._get_value(flag) is None: |
| 1532 |
raise TypeError(f"'{flag}' cannot be combined with other flags with &") |
| 1533 |
value = self._value_ |
| 1534 |
return self.__class__(value & other_value) |
| 1535 |
|
| 1536 |
def __xor__(self, other): |
| 1537 |
other_value = self._get_value(other) |
| 1538 |
if other_value is NotImplemented: |
| 1539 |
return NotImplemented |
| 1540 |
|
| 1541 |
for flag in self, other: |
| 1542 |
if self._get_value(flag) is None: |
| 1543 |
raise TypeError(f"'{flag}' cannot be combined with other flags with ^") |
| 1544 |
value = self._value_ |
| 1545 |
return self.__class__(value ^ other_value) |
| 1546 |
|
| 1547 |
def __invert__(self): |
| 1548 |
if self._get_value(self) is None: |
| 1549 |
raise TypeError(f"'{self}' cannot be inverted") |
| 1550 |
|
| 1551 |
if self._inverted_ is None: |
| 1552 |
if self._boundary_ in (EJECT, KEEP): |
| 1553 |
self._inverted_ = self.__class__(~self._value_) |
| 1554 |
else: |
| 1555 |
self._inverted_ = self.__class__(self._singles_mask_ & ~self._value_) |
| 1556 |
return self._inverted_ |
| 1557 |
|
| 1558 |
__rand__ = __and__ |
| 1559 |
__ror__ = __or__ |
| 1560 |
__rxor__ = __xor__ |
| 1561 |
|
| 1562 |
|
| 1563 |
class IntFlag(int, ReprEnum, Flag, boundary=KEEP): |
| 1564 |
""" |
| 1565 |
Support for integer-based Flags |
| 1566 |
""" |
| 1567 |
|
| 1568 |
|
| 1569 |
def _high_bit(value): |
| 1570 |
""" |
| 1571 |
returns index of highest bit, or -1 if value is zero or negative |
| 1572 |
""" |
| 1573 |
return value.bit_length() - 1 |
| 1574 |
|
| 1575 |
def unique(enumeration): |
| 1576 |
""" |
| 1577 |
Class decorator for enumerations ensuring unique member values. |
| 1578 |
""" |
| 1579 |
duplicates = [] |
| 1580 |
for name, member in enumeration.__members__.items(): |
| 1581 |
if name != member.name: |
| 1582 |
duplicates.append((name, member.name)) |
| 1583 |
if duplicates: |
| 1584 |
alias_details = ', '.join( |
| 1585 |
["%s -> %s" % (alias, name) for (alias, name) in duplicates]) |
| 1586 |
raise ValueError('duplicate values found in %r: %s' % |
| 1587 |
(enumeration, alias_details)) |
| 1588 |
return enumeration |
| 1589 |
|
| 1590 |
def _power_of_two(value): |
| 1591 |
if value < 1: |
| 1592 |
return False |
| 1593 |
return value == 2 ** _high_bit(value) |
| 1594 |
|
| 1595 |
def global_enum_repr(self): |
| 1596 |
""" |
| 1597 |
use module.enum_name instead of class.enum_name |
| 1598 |
|
| 1599 |
the module is the last module in case of a multi-module name |
| 1600 |
""" |
| 1601 |
module = self.__class__.__module__.split('.')[-1] |
| 1602 |
return '%s.%s' % (module, self._name_) |
| 1603 |
|
| 1604 |
def global_flag_repr(self): |
| 1605 |
""" |
| 1606 |
use module.flag_name instead of class.flag_name |
| 1607 |
|
| 1608 |
the module is the last module in case of a multi-module name |
| 1609 |
""" |
| 1610 |
module = self.__class__.__module__.split('.')[-1] |
| 1611 |
cls_name = self.__class__.__name__ |
| 1612 |
if self._name_ is None: |
| 1613 |
return "%s.%s(%r)" % (module, cls_name, self._value_) |
| 1614 |
if _is_single_bit(self._value_): |
| 1615 |
return '%s.%s' % (module, self._name_) |
| 1616 |
if self._boundary_ is not FlagBoundary.KEEP: |
| 1617 |
return '|'.join(['%s.%s' % (module, name) for name in self.name.split('|')]) |
| 1618 |
else: |
| 1619 |
name = [] |
| 1620 |
for n in self._name_.split('|'): |
| 1621 |
if n[0].isdigit(): |
| 1622 |
name.append(n) |
| 1623 |
else: |
| 1624 |
name.append('%s.%s' % (module, n)) |
| 1625 |
return '|'.join(name) |
| 1626 |
|
| 1627 |
def global_str(self): |
| 1628 |
""" |
| 1629 |
use enum_name instead of class.enum_name |
| 1630 |
""" |
| 1631 |
if self._name_ is None: |
| 1632 |
cls_name = self.__class__.__name__ |
| 1633 |
return "%s(%r)" % (cls_name, self._value_) |
| 1634 |
else: |
| 1635 |
return self._name_ |
| 1636 |
|
| 1637 |
def global_enum(cls, update_str=False): |
| 1638 |
""" |
| 1639 |
decorator that makes the repr() of an enum member reference its module |
| 1640 |
instead of its class; also exports all members to the enum's module's |
| 1641 |
global namespace |
| 1642 |
""" |
| 1643 |
if issubclass(cls, Flag): |
| 1644 |
cls.__repr__ = global_flag_repr |
| 1645 |
else: |
| 1646 |
cls.__repr__ = global_enum_repr |
| 1647 |
if not issubclass(cls, ReprEnum) or update_str: |
| 1648 |
cls.__str__ = global_str |
| 1649 |
sys.modules[cls.__module__].__dict__.update(cls.__members__) |
| 1650 |
return cls |
| 1651 |
|
| 1652 |
def _simple_enum(etype=Enum, *, boundary=None, use_args=None): |
| 1653 |
""" |
| 1654 |
Class decorator that converts a normal class into an :class:`Enum`. No |
| 1655 |
safety checks are done, and some advanced behavior (such as |
| 1656 |
:func:`__init_subclass__`) is not available. Enum creation can be faster |
| 1657 |
using :func:`simple_enum`. |
| 1658 |
|
| 1659 |
>>> from enum import Enum, _simple_enum |
| 1660 |
>>> @_simple_enum(Enum) |
| 1661 |
... class Color: |
| 1662 |
... RED = auto() |
| 1663 |
... GREEN = auto() |
| 1664 |
... BLUE = auto() |
| 1665 |
>>> Color |
| 1666 |
<enum 'Color'> |
| 1667 |
""" |
| 1668 |
def convert_class(cls): |
| 1669 |
nonlocal use_args |
| 1670 |
cls_name = cls.__name__ |
| 1671 |
if use_args is None: |
| 1672 |
use_args = etype._use_args_ |
| 1673 |
__new__ = cls.__dict__.get('__new__') |
| 1674 |
if __new__ is not None: |
| 1675 |
new_member = __new__.__func__ |
| 1676 |
else: |
| 1677 |
new_member = etype._member_type_.__new__ |
| 1678 |
attrs = {} |
| 1679 |
body = {} |
| 1680 |
if __new__ is not None: |
| 1681 |
body['__new_member__'] = new_member |
| 1682 |
body['_new_member_'] = new_member |
| 1683 |
body['_use_args_'] = use_args |
| 1684 |
body['_generate_next_value_'] = gnv = etype._generate_next_value_ |
| 1685 |
body['_member_names_'] = member_names = [] |
| 1686 |
body['_member_map_'] = member_map = {} |
| 1687 |
body['_value2member_map_'] = value2member_map = {} |
| 1688 |
body['_unhashable_values_'] = [] |
| 1689 |
body['_member_type_'] = member_type = etype._member_type_ |
| 1690 |
body['_value_repr_'] = etype._value_repr_ |
| 1691 |
if issubclass(etype, Flag): |
| 1692 |
body['_boundary_'] = boundary or etype._boundary_ |
| 1693 |
body['_flag_mask_'] = None |
| 1694 |
body['_all_bits_'] = None |
| 1695 |
body['_singles_mask_'] = None |
| 1696 |
body['_inverted_'] = None |
| 1697 |
body['__or__'] = Flag.__or__ |
| 1698 |
body['__xor__'] = Flag.__xor__ |
| 1699 |
body['__and__'] = Flag.__and__ |
| 1700 |
body['__ror__'] = Flag.__ror__ |
| 1701 |
body['__rxor__'] = Flag.__rxor__ |
| 1702 |
body['__rand__'] = Flag.__rand__ |
| 1703 |
body['__invert__'] = Flag.__invert__ |
| 1704 |
for name, obj in cls.__dict__.items(): |
| 1705 |
if name in ('__dict__', '__weakref__'): |
| 1706 |
continue |
| 1707 |
if _is_dunder(name) or _is_private(cls_name, name) or _is_sunder(name) or _is_descriptor(obj): |
| 1708 |
body[name] = obj |
| 1709 |
else: |
| 1710 |
attrs[name] = obj |
| 1711 |
if cls.__dict__.get('__doc__') is None: |
| 1712 |
body['__doc__'] = 'An enumeration.' |
| 1713 |
|
| 1714 |
|
| 1715 |
|
| 1716 |
|
| 1717 |
|
| 1718 |
enum_class = type(cls_name, (etype, ), body, boundary=boundary, _simple=True) |
| 1719 |
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): |
| 1720 |
if name not in body: |
| 1721 |
|
| 1722 |
enum_method = getattr(etype, name) |
| 1723 |
found_method = getattr(enum_class, name) |
| 1724 |
object_method = getattr(object, name) |
| 1725 |
data_type_method = getattr(member_type, name) |
| 1726 |
if found_method in (data_type_method, object_method): |
| 1727 |
setattr(enum_class, name, enum_method) |
| 1728 |
gnv_last_values = [] |
| 1729 |
if issubclass(enum_class, Flag): |
| 1730 |
|
| 1731 |
single_bits = multi_bits = 0 |
| 1732 |
for name, value in attrs.items(): |
| 1733 |
if isinstance(value, auto) and auto.value is _auto_null: |
| 1734 |
value = gnv(name, 1, len(member_names), gnv_last_values) |
| 1735 |
if value in value2member_map: |
| 1736 |
|
| 1737 |
redirect = property() |
| 1738 |
redirect.__set_name__(enum_class, name) |
| 1739 |
setattr(enum_class, name, redirect) |
| 1740 |
member_map[name] = value2member_map[value] |
| 1741 |
else: |
| 1742 |
|
| 1743 |
if use_args: |
| 1744 |
if not isinstance(value, tuple): |
| 1745 |
value = (value, ) |
| 1746 |
member = new_member(enum_class, *value) |
| 1747 |
value = value[0] |
| 1748 |
else: |
| 1749 |
member = new_member(enum_class) |
| 1750 |
if __new__ is None: |
| 1751 |
member._value_ = value |
| 1752 |
member._name_ = name |
| 1753 |
member.__objclass__ = enum_class |
| 1754 |
member.__init__(value) |
| 1755 |
redirect = property() |
| 1756 |
redirect.__set_name__(enum_class, name) |
| 1757 |
setattr(enum_class, name, redirect) |
| 1758 |
member_map[name] = member |
| 1759 |
member._sort_order_ = len(member_names) |
| 1760 |
value2member_map[value] = member |
| 1761 |
if _is_single_bit(value): |
| 1762 |
|
| 1763 |
member_names.append(name) |
| 1764 |
single_bits |= value |
| 1765 |
else: |
| 1766 |
multi_bits |= value |
| 1767 |
gnv_last_values.append(value) |
| 1768 |
enum_class._flag_mask_ = single_bits | multi_bits |
| 1769 |
enum_class._singles_mask_ = single_bits |
| 1770 |
enum_class._all_bits_ = 2 ** ((single_bits|multi_bits).bit_length()) - 1 |
| 1771 |
|
| 1772 |
member_list = [m._value_ for m in enum_class] |
| 1773 |
if member_list != sorted(member_list): |
| 1774 |
enum_class._iter_member_ = enum_class._iter_member_by_def_ |
| 1775 |
else: |
| 1776 |
|
| 1777 |
for name, value in attrs.items(): |
| 1778 |
if isinstance(value, auto): |
| 1779 |
if value.value is _auto_null: |
| 1780 |
value.value = gnv(name, 1, len(member_names), gnv_last_values) |
| 1781 |
value = value.value |
| 1782 |
if value in value2member_map: |
| 1783 |
|
| 1784 |
redirect = property() |
| 1785 |
redirect.__set_name__(enum_class, name) |
| 1786 |
setattr(enum_class, name, redirect) |
| 1787 |
member_map[name] = value2member_map[value] |
| 1788 |
else: |
| 1789 |
|
| 1790 |
if use_args: |
| 1791 |
if not isinstance(value, tuple): |
| 1792 |
value = (value, ) |
| 1793 |
member = new_member(enum_class, *value) |
| 1794 |
value = value[0] |
| 1795 |
else: |
| 1796 |
member = new_member(enum_class) |
| 1797 |
if __new__ is None: |
| 1798 |
member._value_ = value |
| 1799 |
member._name_ = name |
| 1800 |
member.__objclass__ = enum_class |
| 1801 |
member.__init__(value) |
| 1802 |
member._sort_order_ = len(member_names) |
| 1803 |
redirect = property() |
| 1804 |
redirect.__set_name__(enum_class, name) |
| 1805 |
setattr(enum_class, name, redirect) |
| 1806 |
member_map[name] = member |
| 1807 |
value2member_map[value] = member |
| 1808 |
member_names.append(name) |
| 1809 |
gnv_last_values.append(value) |
| 1810 |
if '__new__' in body: |
| 1811 |
enum_class.__new_member__ = enum_class.__new__ |
| 1812 |
enum_class.__new__ = Enum.__new__ |
| 1813 |
return enum_class |
| 1814 |
return convert_class |
| 1815 |
|
| 1816 |
@_simple_enum(StrEnum) |
| 1817 |
class EnumCheck: |
| 1818 |
""" |
| 1819 |
various conditions to check an enumeration for |
| 1820 |
""" |
| 1821 |
CONTINUOUS = "no skipped integer values" |
| 1822 |
NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags" |
| 1823 |
UNIQUE = "one name per value" |
| 1824 |
CONTINUOUS, NAMED_FLAGS, UNIQUE = EnumCheck |
| 1825 |
|
| 1826 |
|
| 1827 |
class verify: |
| 1828 |
""" |
| 1829 |
Check an enumeration for various constraints. (see EnumCheck) |
| 1830 |
""" |
| 1831 |
def __init__(self, *checks): |
| 1832 |
self.checks = checks |
| 1833 |
def __call__(self, enumeration): |
| 1834 |
checks = self.checks |
| 1835 |
cls_name = enumeration.__name__ |
| 1836 |
if Flag is not None and issubclass(enumeration, Flag): |
| 1837 |
enum_type = 'flag' |
| 1838 |
elif issubclass(enumeration, Enum): |
| 1839 |
enum_type = 'enum' |
| 1840 |
else: |
| 1841 |
raise TypeError("the 'verify' decorator only works with Enum and Flag") |
| 1842 |
for check in checks: |
| 1843 |
if check is UNIQUE: |
| 1844 |
|
| 1845 |
duplicates = [] |
| 1846 |
for name, member in enumeration.__members__.items(): |
| 1847 |
if name != member.name: |
| 1848 |
duplicates.append((name, member.name)) |
| 1849 |
if duplicates: |
| 1850 |
alias_details = ', '.join( |
| 1851 |
["%s -> %s" % (alias, name) for (alias, name) in duplicates]) |
| 1852 |
raise ValueError('aliases found in %r: %s' % |
| 1853 |
(enumeration, alias_details)) |
| 1854 |
elif check is CONTINUOUS: |
| 1855 |
values = set(e.value for e in enumeration) |
| 1856 |
if len(values) < 2: |
| 1857 |
continue |
| 1858 |
low, high = min(values), max(values) |
| 1859 |
missing = [] |
| 1860 |
if enum_type == 'flag': |
| 1861 |
|
| 1862 |
for i in range(_high_bit(low)+1, _high_bit(high)): |
| 1863 |
if 2**i not in values: |
| 1864 |
missing.append(2**i) |
| 1865 |
elif enum_type == 'enum': |
| 1866 |
|
| 1867 |
for i in range(low+1, high): |
| 1868 |
if i not in values: |
| 1869 |
missing.append(i) |
| 1870 |
else: |
| 1871 |
raise Exception('verify: unknown type %r' % enum_type) |
| 1872 |
if missing: |
| 1873 |
raise ValueError(('invalid %s %r: missing values %s' % ( |
| 1874 |
enum_type, cls_name, ', '.join((str(m) for m in missing))) |
| 1875 |
)[:256]) |
| 1876 |
|
| 1877 |
elif check is NAMED_FLAGS: |
| 1878 |
|
| 1879 |
member_names = enumeration._member_names_ |
| 1880 |
member_values = [m.value for m in enumeration] |
| 1881 |
missing_names = [] |
| 1882 |
missing_value = 0 |
| 1883 |
for name, alias in enumeration._member_map_.items(): |
| 1884 |
if name in member_names: |
| 1885 |
|
| 1886 |
continue |
| 1887 |
if alias.value < 0: |
| 1888 |
|
| 1889 |
continue |
| 1890 |
values = list(_iter_bits_lsb(alias.value)) |
| 1891 |
missed = [v for v in values if v not in member_values] |
| 1892 |
if missed: |
| 1893 |
missing_names.append(name) |
| 1894 |
missing_value |= reduce(_or_, missed) |
| 1895 |
if missing_names: |
| 1896 |
if len(missing_names) == 1: |
| 1897 |
alias = 'alias %s is missing' % missing_names[0] |
| 1898 |
else: |
| 1899 |
alias = 'aliases %s and %s are missing' % ( |
| 1900 |
', '.join(missing_names[:-1]), missing_names[-1] |
| 1901 |
) |
| 1902 |
if _is_single_bit(missing_value): |
| 1903 |
value = 'value 0x%x' % missing_value |
| 1904 |
else: |
| 1905 |
value = 'combined values of 0x%x' % missing_value |
| 1906 |
raise ValueError( |
| 1907 |
'invalid Flag %r: %s %s [use enum.show_flag_values(value) for details]' |
| 1908 |
% (cls_name, alias, value) |
| 1909 |
) |
| 1910 |
return enumeration |
| 1911 |
|
| 1912 |
def _test_simple_enum(checked_enum, simple_enum): |
| 1913 |
""" |
| 1914 |
A function that can be used to test an enum created with :func:`_simple_enum` |
| 1915 |
against the version created by subclassing :class:`Enum`:: |
| 1916 |
|
| 1917 |
>>> from enum import Enum, _simple_enum, _test_simple_enum |
| 1918 |
>>> @_simple_enum(Enum) |
| 1919 |
... class Color: |
| 1920 |
... RED = auto() |
| 1921 |
... GREEN = auto() |
| 1922 |
... BLUE = auto() |
| 1923 |
>>> class CheckedColor(Enum): |
| 1924 |
... RED = auto() |
| 1925 |
... GREEN = auto() |
| 1926 |
... BLUE = auto() |
| 1927 |
>>> _test_simple_enum(CheckedColor, Color) |
| 1928 |
|
| 1929 |
If differences are found, a :exc:`TypeError` is raised. |
| 1930 |
""" |
| 1931 |
failed = [] |
| 1932 |
if checked_enum.__dict__ != simple_enum.__dict__: |
| 1933 |
checked_dict = checked_enum.__dict__ |
| 1934 |
checked_keys = list(checked_dict.keys()) |
| 1935 |
simple_dict = simple_enum.__dict__ |
| 1936 |
simple_keys = list(simple_dict.keys()) |
| 1937 |
member_names = set( |
| 1938 |
list(checked_enum._member_map_.keys()) |
| 1939 |
+ list(simple_enum._member_map_.keys()) |
| 1940 |
) |
| 1941 |
for key in set(checked_keys + simple_keys): |
| 1942 |
if key in ('__module__', '_member_map_', '_value2member_map_', '__doc__'): |
| 1943 |
|
| 1944 |
continue |
| 1945 |
elif key in member_names: |
| 1946 |
|
| 1947 |
continue |
| 1948 |
elif key not in simple_keys: |
| 1949 |
failed.append("missing key: %r" % (key, )) |
| 1950 |
elif key not in checked_keys: |
| 1951 |
failed.append("extra key: %r" % (key, )) |
| 1952 |
else: |
| 1953 |
checked_value = checked_dict[key] |
| 1954 |
simple_value = simple_dict[key] |
| 1955 |
if callable(checked_value) or isinstance(checked_value, bltns.property): |
| 1956 |
continue |
| 1957 |
if key == '__doc__': |
| 1958 |
|
| 1959 |
compressed_checked_value = checked_value.replace(' ','').replace('\t','') |
| 1960 |
compressed_simple_value = simple_value.replace(' ','').replace('\t','') |
| 1961 |
if compressed_checked_value != compressed_simple_value: |
| 1962 |
failed.append("%r:\n %s\n %s" % ( |
| 1963 |
key, |
| 1964 |
"checked -> %r" % (checked_value, ), |
| 1965 |
"simple -> %r" % (simple_value, ), |
| 1966 |
)) |
| 1967 |
elif checked_value != simple_value: |
| 1968 |
failed.append("%r:\n %s\n %s" % ( |
| 1969 |
key, |
| 1970 |
"checked -> %r" % (checked_value, ), |
| 1971 |
"simple -> %r" % (simple_value, ), |
| 1972 |
)) |
| 1973 |
failed.sort() |
| 1974 |
for name in member_names: |
| 1975 |
failed_member = [] |
| 1976 |
if name not in simple_keys: |
| 1977 |
failed.append('missing member from simple enum: %r' % name) |
| 1978 |
elif name not in checked_keys: |
| 1979 |
failed.append('extra member in simple enum: %r' % name) |
| 1980 |
else: |
| 1981 |
checked_member_dict = checked_enum[name].__dict__ |
| 1982 |
checked_member_keys = list(checked_member_dict.keys()) |
| 1983 |
simple_member_dict = simple_enum[name].__dict__ |
| 1984 |
simple_member_keys = list(simple_member_dict.keys()) |
| 1985 |
for key in set(checked_member_keys + simple_member_keys): |
| 1986 |
if key in ('__module__', '__objclass__', '_inverted_'): |
| 1987 |
|
| 1988 |
continue |
| 1989 |
elif key not in simple_member_keys: |
| 1990 |
failed_member.append("missing key %r not in the simple enum member %r" % (key, name)) |
| 1991 |
elif key not in checked_member_keys: |
| 1992 |
failed_member.append("extra key %r in simple enum member %r" % (key, name)) |
| 1993 |
else: |
| 1994 |
checked_value = checked_member_dict[key] |
| 1995 |
simple_value = simple_member_dict[key] |
| 1996 |
if checked_value != simple_value: |
| 1997 |
failed_member.append("%r:\n %s\n %s" % ( |
| 1998 |
key, |
| 1999 |
"checked member -> %r" % (checked_value, ), |
| 2000 |
"simple member -> %r" % (simple_value, ), |
| 2001 |
)) |
| 2002 |
if failed_member: |
| 2003 |
failed.append('%r member mismatch:\n %s' % ( |
| 2004 |
name, '\n '.join(failed_member), |
| 2005 |
)) |
| 2006 |
for method in ( |
| 2007 |
'__str__', '__repr__', '__reduce_ex__', '__format__', |
| 2008 |
'__getnewargs_ex__', '__getnewargs__', '__reduce_ex__', '__reduce__' |
| 2009 |
): |
| 2010 |
if method in simple_keys and method in checked_keys: |
| 2011 |
|
| 2012 |
continue |
| 2013 |
elif method not in simple_keys and method not in checked_keys: |
| 2014 |
|
| 2015 |
checked_method = getattr(checked_enum, method, None) |
| 2016 |
simple_method = getattr(simple_enum, method, None) |
| 2017 |
if hasattr(checked_method, '__func__'): |
| 2018 |
checked_method = checked_method.__func__ |
| 2019 |
simple_method = simple_method.__func__ |
| 2020 |
if checked_method != simple_method: |
| 2021 |
failed.append("%r: %-30s %s" % ( |
| 2022 |
method, |
| 2023 |
"checked -> %r" % (checked_method, ), |
| 2024 |
"simple -> %r" % (simple_method, ), |
| 2025 |
)) |
| 2026 |
else: |
| 2027 |
|
| 2028 |
|
| 2029 |
pass |
| 2030 |
if failed: |
| 2031 |
raise TypeError('enum mismatch:\n %s' % '\n '.join(failed)) |
| 2032 |
|
| 2033 |
def _old_convert_(etype, name, module, filter, source=None, *, boundary=None): |
| 2034 |
""" |
| 2035 |
Create a new Enum subclass that replaces a collection of global constants |
| 2036 |
""" |
| 2037 |
|
| 2038 |
|
| 2039 |
|
| 2040 |
|
| 2041 |
|
| 2042 |
module_globals = sys.modules[module].__dict__ |
| 2043 |
if source: |
| 2044 |
source = source.__dict__ |
| 2045 |
else: |
| 2046 |
source = module_globals |
| 2047 |
|
| 2048 |
|
| 2049 |
|
| 2050 |
members = [ |
| 2051 |
(name, value) |
| 2052 |
for name, value in source.items() |
| 2053 |
if filter(name)] |
| 2054 |
try: |
| 2055 |
|
| 2056 |
members.sort(key=lambda t: (t[1], t[0])) |
| 2057 |
except TypeError: |
| 2058 |
|
| 2059 |
members.sort(key=lambda t: t[0]) |
| 2060 |
cls = etype(name, members, module=module, boundary=boundary or KEEP) |
| 2061 |
return cls |
| 2062 |
|
| 2063 |
_stdlib_enums = IntEnum, StrEnum, IntFlag |