-
-
Notifications
You must be signed in to change notification settings - Fork 30.8k
/
enum.py
2170 lines (1982 loc) · 82.9 KB
/
enum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import builtins as bltns
from types import MappingProxyType, DynamicClassAttribute
__all__ = [
'EnumType', 'EnumMeta', 'EnumDict',
'Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag', 'ReprEnum',
'auto', 'unique', 'property', 'verify', 'member', 'nonmember',
'FlagBoundary', 'STRICT', 'CONFORM', 'EJECT', 'KEEP',
'global_flag_repr', 'global_enum_repr', 'global_str', 'global_enum',
'EnumCheck', 'CONTINUOUS', 'NAMED_FLAGS', 'UNIQUE',
'pickle_by_global_name', 'pickle_by_enum_name',
]
# Dummy value for Enum and Flag as there are explicit checks for them
# before they have been created.
# This is also why there are checks in EnumType like `if Enum is not None`
Enum = Flag = EJECT = _stdlib_enums = ReprEnum = None
class nonmember(object):
"""
Protects item from becoming an Enum member during class creation.
"""
def __init__(self, value):
self.value = value
class member(object):
"""
Forces item to become an Enum member during class creation.
"""
def __init__(self, value):
self.value = value
def _is_descriptor(obj):
"""
Returns True if obj is a descriptor, False otherwise.
"""
return (
hasattr(obj, '__get__') or
hasattr(obj, '__set__') or
hasattr(obj, '__delete__')
)
def _is_dunder(name):
"""
Returns True if a __dunder__ name, False otherwise.
"""
return (
len(name) > 4 and
name[:2] == name[-2:] == '__' and
name[2] != '_' and
name[-3] != '_'
)
def _is_sunder(name):
"""
Returns True if a _sunder_ name, False otherwise.
"""
return (
len(name) > 2 and
name[0] == name[-1] == '_' and
name[1] != '_' and
name[-2] != '_'
)
def _is_internal_class(cls_name, obj):
# do not use `re` as `re` imports `enum`
if not isinstance(obj, type):
return False
qualname = getattr(obj, '__qualname__', '')
s_pattern = cls_name + '.' + getattr(obj, '__name__', '')
e_pattern = '.' + s_pattern
return qualname == s_pattern or qualname.endswith(e_pattern)
def _is_private(cls_name, name):
# do not use `re` as `re` imports `enum`
pattern = '_%s__' % (cls_name, )
pat_len = len(pattern)
if (
len(name) > pat_len
and name.startswith(pattern)
and (name[-1] != '_' or name[-2] != '_')
):
return True
else:
return False
def _is_single_bit(num):
"""
True if only one bit set in num (should be an int)
"""
if num == 0:
return False
num &= num - 1
return num == 0
def _make_class_unpicklable(obj):
"""
Make the given obj un-picklable.
obj should be either a dictionary, or an Enum
"""
def _break_on_call_reduce(self, proto):
raise TypeError('%r cannot be pickled' % self)
if isinstance(obj, dict):
obj['__reduce_ex__'] = _break_on_call_reduce
obj['__module__'] = '<unknown>'
else:
setattr(obj, '__reduce_ex__', _break_on_call_reduce)
setattr(obj, '__module__', '<unknown>')
def _iter_bits_lsb(num):
# num must be a positive integer
original = num
if isinstance(num, Enum):
num = num.value
if num < 0:
raise ValueError('%r is not a positive integer' % original)
while num:
b = num & (~num + 1)
yield b
num ^= b
def show_flag_values(value):
return list(_iter_bits_lsb(value))
def bin(num, max_bits=None):
"""
Like built-in bin(), except negative values are represented in
twos-compliment, and the leading bit always indicates sign
(0=positive, 1=negative).
>>> bin(10)
'0b0 1010'
>>> bin(~10) # ~10 is -11
'0b1 0101'
"""
ceiling = 2 ** (num).bit_length()
if num >= 0:
s = bltns.bin(num + ceiling).replace('1', '0', 1)
else:
s = bltns.bin(~num ^ (ceiling - 1) + ceiling)
sign = s[:3]
digits = s[3:]
if max_bits is not None:
if len(digits) < max_bits:
digits = (sign[-1] * max_bits + digits)[-max_bits:]
return "%s %s" % (sign, digits)
def _dedent(text):
"""
Like textwrap.dedent. Rewritten because we cannot import textwrap.
"""
lines = text.split('\n')
for i, ch in enumerate(lines[0]):
if ch != ' ':
break
for j, l in enumerate(lines):
lines[j] = l[i:]
return '\n'.join(lines)
class _not_given:
def __repr__(self):
return('<not given>')
_not_given = _not_given()
class _auto_null:
def __repr__(self):
return '_auto_null'
_auto_null = _auto_null()
class auto:
"""
Instances are replaced with an appropriate value in Enum class suites.
"""
def __init__(self, value=_auto_null):
self.value = value
def __repr__(self):
return "auto(%r)" % self.value
class property(DynamicClassAttribute):
"""
This is a descriptor, used to define attributes that act differently
when accessed through an enum member and through an enum class.
Instance access is the same as property(), but access to an attribute
through the enum class will instead look in the class' _member_map_ for
a corresponding enum member.
"""
member = None
_attr_type = None
_cls_type = None
def __get__(self, instance, ownerclass=None):
if instance is None:
if self.member is not None:
return self.member
else:
raise AttributeError(
'%r has no attribute %r' % (ownerclass, self.name)
)
if self.fget is not None:
# use previous enum.property
return self.fget(instance)
elif self._attr_type == 'attr':
# look up previous attribute
return getattr(self._cls_type, self.name)
elif self._attr_type == 'desc':
# use previous descriptor
return getattr(instance._value_, self.name)
# look for a member by this name.
try:
return ownerclass._member_map_[self.name]
except KeyError:
raise AttributeError(
'%r has no attribute %r' % (ownerclass, self.name)
) from None
def __set__(self, instance, value):
if self.fset is not None:
return self.fset(instance, value)
raise AttributeError(
"<enum %r> cannot set attribute %r" % (self.clsname, self.name)
)
def __delete__(self, instance):
if self.fdel is not None:
return self.fdel(instance)
raise AttributeError(
"<enum %r> cannot delete attribute %r" % (self.clsname, self.name)
)
def __set_name__(self, ownerclass, name):
self.name = name
self.clsname = ownerclass.__name__
class _proto_member:
"""
intermediate step for enum members between class execution and final creation
"""
def __init__(self, value):
self.value = value
def __set_name__(self, enum_class, member_name):
"""
convert each quasi-member into an instance of the new enum class
"""
# first step: remove ourself from enum_class
delattr(enum_class, member_name)
# second step: create member based on enum_class
value = self.value
if not isinstance(value, tuple):
args = (value, )
else:
args = value
if enum_class._member_type_ is tuple: # special case for tuple enums
args = (args, ) # wrap it one more time
if not enum_class._use_args_:
enum_member = enum_class._new_member_(enum_class)
else:
enum_member = enum_class._new_member_(enum_class, *args)
if not hasattr(enum_member, '_value_'):
if enum_class._member_type_ is object:
enum_member._value_ = value
else:
try:
enum_member._value_ = enum_class._member_type_(*args)
except Exception as exc:
new_exc = TypeError(
'_value_ not set in __new__, unable to create it'
)
new_exc.__cause__ = exc
raise new_exc
value = enum_member._value_
enum_member._name_ = member_name
enum_member.__objclass__ = enum_class
enum_member.__init__(*args)
enum_member._sort_order_ = len(enum_class._member_names_)
if Flag is not None and issubclass(enum_class, Flag):
if isinstance(value, int):
enum_class._flag_mask_ |= value
if _is_single_bit(value):
enum_class._singles_mask_ |= value
enum_class._all_bits_ = 2 ** ((enum_class._flag_mask_).bit_length()) - 1
# If another member with the same value was already defined, the
# new member becomes an alias to the existing one.
try:
try:
# try to do a fast lookup to avoid the quadratic loop
enum_member = enum_class._value2member_map_[value]
except TypeError:
for name, canonical_member in enum_class._member_map_.items():
if canonical_member._value_ == value:
enum_member = canonical_member
break
else:
raise KeyError
except KeyError:
# this could still be an alias if the value is multi-bit and the
# class is a flag class
if (
Flag is None
or not issubclass(enum_class, Flag)
):
# no other instances found, record this member in _member_names_
enum_class._member_names_.append(member_name)
elif (
Flag is not None
and issubclass(enum_class, Flag)
and isinstance(value, int)
and _is_single_bit(value)
):
# no other instances found, record this member in _member_names_
enum_class._member_names_.append(member_name)
enum_class._add_member_(member_name, enum_member)
try:
# This may fail if value is not hashable. We can't add the value
# to the map, and by-value lookups for this value will be
# linear.
enum_class._value2member_map_.setdefault(value, enum_member)
except TypeError:
# keep track of the value in a list so containment checks are quick
enum_class._unhashable_values_.append(value)
enum_class._unhashable_values_map_.setdefault(member_name, []).append(value)
class EnumDict(dict):
"""
Track enum member order and ensure member names are not reused.
EnumType will use the names found in self._member_names as the
enumeration member names.
"""
def __init__(self):
super().__init__()
self._member_names = {} # use a dict -- faster look-up than a list, and keeps insertion order since 3.7
self._last_values = []
self._ignore = []
self._auto_called = False
def __setitem__(self, key, value):
"""
Changes anything not dundered or not a descriptor.
If an enum member name is used twice, an error is raised; duplicate
values are not checked for.
Single underscore (sunder) names are reserved.
"""
if _is_private(self._cls_name, key):
# do nothing, name will be a normal attribute
pass
elif _is_sunder(key):
if key not in (
'_order_',
'_generate_next_value_', '_numeric_repr_', '_missing_', '_ignore_',
'_iter_member_', '_iter_member_by_value_', '_iter_member_by_def_',
'_add_alias_', '_add_value_alias_',
# While not in use internally, those are common for pretty
# printing and thus excluded from Enum's reservation of
# _sunder_ names
) and not key.startswith('_repr_'):
raise ValueError(
'_sunder_ names, such as %r, are reserved for future Enum use'
% (key, )
)
if key == '_generate_next_value_':
# check if members already defined as auto()
if self._auto_called:
raise TypeError("_generate_next_value_ must be defined before members")
_gnv = value.__func__ if isinstance(value, staticmethod) else value
setattr(self, '_generate_next_value', _gnv)
elif key == '_ignore_':
if isinstance(value, str):
value = value.replace(',',' ').split()
else:
value = list(value)
self._ignore = value
already = set(value) & set(self._member_names)
if already:
raise ValueError(
'_ignore_ cannot specify already set names: %r'
% (already, )
)
elif _is_dunder(key):
if key == '__order__':
key = '_order_'
elif key in self._member_names:
# descriptor overwriting an enum?
raise TypeError('%r already defined as %r' % (key, self[key]))
elif key in self._ignore:
pass
elif isinstance(value, nonmember):
# unwrap value here; it won't be processed by the below `else`
value = value.value
elif _is_descriptor(value):
pass
elif _is_internal_class(self._cls_name, value):
# do nothing, name will be a normal attribute
pass
else:
if key in self:
# enum overwriting a descriptor?
raise TypeError('%r already defined as %r' % (key, self[key]))
elif isinstance(value, member):
# unwrap value here -- it will become a member
value = value.value
non_auto_store = True
single = False
if isinstance(value, auto):
single = True
value = (value, )
if isinstance(value, tuple) and any(isinstance(v, auto) for v in value):
# insist on an actual tuple, no subclasses, in keeping with only supporting
# top-level auto() usage (not contained in any other data structure)
auto_valued = []
t = type(value)
for v in value:
if isinstance(v, auto):
non_auto_store = False
if v.value == _auto_null:
v.value = self._generate_next_value(
key, 1, len(self._member_names), self._last_values[:],
)
self._auto_called = True
v = v.value
self._last_values.append(v)
auto_valued.append(v)
if single:
value = auto_valued[0]
else:
try:
# accepts iterable as multiple arguments?
value = t(auto_valued)
except TypeError:
# then pass them in singly
value = t(*auto_valued)
self._member_names[key] = None
if non_auto_store:
self._last_values.append(value)
super().__setitem__(key, value)
@property
def member_names(self):
return list(self._member_names)
def update(self, members, **more_members):
try:
for name in members.keys():
self[name] = members[name]
except AttributeError:
for name, value in members:
self[name] = value
for name, value in more_members.items():
self[name] = value
_EnumDict = EnumDict # keep private name for backwards compatibility
class EnumType(type):
"""
Metaclass for Enum
"""
@classmethod
def __prepare__(metacls, cls, bases, **kwds):
# check that previous enum members do not exist
metacls._check_for_existing_members_(cls, bases)
# create the namespace dict
enum_dict = EnumDict()
enum_dict._cls_name = cls
# inherit previous flags and _generate_next_value_ function
member_type, first_enum = metacls._get_mixins_(cls, bases)
if first_enum is not None:
enum_dict['_generate_next_value_'] = getattr(
first_enum, '_generate_next_value_', None,
)
return enum_dict
def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **kwds):
# an Enum class is final once enumeration items have been defined; it
# cannot be mixed with other types (int, float, etc.) if it has an
# inherited __new__ unless a new __new__ is defined (or the resulting
# class will fail).
#
if _simple:
return super().__new__(metacls, cls, bases, classdict, **kwds)
#
# remove any keys listed in _ignore_
classdict.setdefault('_ignore_', []).append('_ignore_')
ignore = classdict['_ignore_']
for key in ignore:
classdict.pop(key, None)
#
# grab member names
member_names = classdict._member_names
#
# check for illegal enum names (any others?)
invalid_names = set(member_names) & {'mro', ''}
if invalid_names:
raise ValueError('invalid enum member name(s) %s' % (
','.join(repr(n) for n in invalid_names)
))
#
# adjust the sunders
_order_ = classdict.pop('_order_', None)
_gnv = classdict.get('_generate_next_value_')
if _gnv is not None and type(_gnv) is not staticmethod:
_gnv = staticmethod(_gnv)
# convert to normal dict
classdict = dict(classdict.items())
if _gnv is not None:
classdict['_generate_next_value_'] = _gnv
#
# data type of member and the controlling Enum class
member_type, first_enum = metacls._get_mixins_(cls, bases)
__new__, save_new, use_args = metacls._find_new_(
classdict, member_type, first_enum,
)
classdict['_new_member_'] = __new__
classdict['_use_args_'] = use_args
#
# convert future enum members into temporary _proto_members
for name in member_names:
value = classdict[name]
classdict[name] = _proto_member(value)
#
# house-keeping structures
classdict['_member_names_'] = []
classdict['_member_map_'] = {}
classdict['_value2member_map_'] = {}
classdict['_unhashable_values_'] = []
classdict['_unhashable_values_map_'] = {}
classdict['_member_type_'] = member_type
# now set the __repr__ for the value
classdict['_value_repr_'] = metacls._find_data_repr_(cls, bases)
#
# Flag structures (will be removed if final class is not a Flag
classdict['_boundary_'] = (
boundary
or getattr(first_enum, '_boundary_', None)
)
classdict['_flag_mask_'] = 0
classdict['_singles_mask_'] = 0
classdict['_all_bits_'] = 0
classdict['_inverted_'] = None
try:
exc = None
classdict['_%s__in_progress' % cls] = True
enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
classdict['_%s__in_progress' % cls] = False
delattr(enum_class, '_%s__in_progress' % cls)
except Exception as e:
# since 3.12 the line "Error calling __set_name__ on '_proto_member' instance ..."
# is tacked on to the error instead of raising a RuntimeError
# recreate the exception to discard
exc = type(e)(str(e))
exc.__cause__ = e.__cause__
exc.__context__ = e.__context__
tb = e.__traceback__
if exc is not None:
raise exc.with_traceback(tb)
#
# update classdict with any changes made by __init_subclass__
classdict.update(enum_class.__dict__)
#
# double check that repr and friends are not the mixin's or various
# things break (such as pickle)
# however, if the method is defined in the Enum itself, don't replace
# it
#
# Also, special handling for ReprEnum
if ReprEnum is not None and ReprEnum in bases:
if member_type is object:
raise TypeError(
'ReprEnum subclasses must be mixed with a data type (i.e.'
' int, str, float, etc.)'
)
if '__format__' not in classdict:
enum_class.__format__ = member_type.__format__
classdict['__format__'] = enum_class.__format__
if '__str__' not in classdict:
method = member_type.__str__
if method is object.__str__:
# if member_type does not define __str__, object.__str__ will use
# its __repr__ instead, so we'll also use its __repr__
method = member_type.__repr__
enum_class.__str__ = method
classdict['__str__'] = enum_class.__str__
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
if name not in classdict:
# check for mixin overrides before replacing
enum_method = getattr(first_enum, name)
found_method = getattr(enum_class, name)
object_method = getattr(object, name)
data_type_method = getattr(member_type, name)
if found_method in (data_type_method, object_method):
setattr(enum_class, name, enum_method)
#
# for Flag, add __or__, __and__, __xor__, and __invert__
if Flag is not None and issubclass(enum_class, Flag):
for name in (
'__or__', '__and__', '__xor__',
'__ror__', '__rand__', '__rxor__',
'__invert__'
):
if name not in classdict:
enum_method = getattr(Flag, name)
setattr(enum_class, name, enum_method)
classdict[name] = enum_method
#
# replace any other __new__ with our own (as long as Enum is not None,
# anyway) -- again, this is to support pickle
if Enum is not None:
# if the user defined their own __new__, save it before it gets
# clobbered in case they subclass later
if save_new:
enum_class.__new_member__ = __new__
enum_class.__new__ = Enum.__new__
#
# py3 support for definition order (helps keep py2/py3 code in sync)
#
# _order_ checking is spread out into three/four steps
# - if enum_class is a Flag:
# - remove any non-single-bit flags from _order_
# - remove any aliases from _order_
# - check that _order_ and _member_names_ match
#
# step 1: ensure we have a list
if _order_ is not None:
if isinstance(_order_, str):
_order_ = _order_.replace(',', ' ').split()
#
# remove Flag structures if final class is not a Flag
if (
Flag is None and cls != 'Flag'
or Flag is not None and not issubclass(enum_class, Flag)
):
delattr(enum_class, '_boundary_')
delattr(enum_class, '_flag_mask_')
delattr(enum_class, '_singles_mask_')
delattr(enum_class, '_all_bits_')
delattr(enum_class, '_inverted_')
elif Flag is not None and issubclass(enum_class, Flag):
# set correct __iter__
member_list = [m._value_ for m in enum_class]
if member_list != sorted(member_list):
enum_class._iter_member_ = enum_class._iter_member_by_def_
if _order_:
# _order_ step 2: remove any items from _order_ that are not single-bit
_order_ = [
o
for o in _order_
if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_)
]
#
if _order_:
# _order_ step 3: remove aliases from _order_
_order_ = [
o
for o in _order_
if (
o not in enum_class._member_map_
or
(o in enum_class._member_map_ and o in enum_class._member_names_)
)]
# _order_ step 4: verify that _order_ and _member_names_ match
if _order_ != enum_class._member_names_:
raise TypeError(
'member order does not match _order_:\n %r\n %r'
% (enum_class._member_names_, _order_)
)
#
return enum_class
def __bool__(cls):
"""
classes/types should always be True.
"""
return True
def __call__(cls, value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None):
"""
Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
(i.e. Color = Enum('Color', names='RED GREEN BLUE')).
The value lookup branch is chosen if the enum is final.
When used for the functional API:
`value` will be the name of the new class.
`names` should be either a string of white-space/comma delimited names
(values will start at `start`), or an iterator/mapping of name, value pairs.
`module` should be set to the module this class is being created in;
if it is not set, an attempt to find that module will be made, but if
it fails the class will not be picklable.
`qualname` should be set to the actual location this class can be found
at in its module; by default it is set to the global scope. If this is
not correct, unpickling will fail in some circumstances.
`type`, if set, will be mixed in as the first base class.
"""
if cls._member_map_:
# simple value lookup if members exist
if names is not _not_given:
value = (value, names) + values
return cls.__new__(cls, value)
# otherwise, functional API: we're creating a new Enum type
if names is _not_given and type is None:
# no body? no data-type? possibly wrong usage
raise TypeError(
f"{cls} has no members; specify `names=()` if you meant to create a new, empty, enum"
)
return cls._create_(
class_name=value,
names=None if names is _not_given else names,
module=module,
qualname=qualname,
type=type,
start=start,
boundary=boundary,
)
def __contains__(cls, value):
"""Return True if `value` is in `cls`.
`value` is in `cls` if:
1) `value` is a member of `cls`, or
2) `value` is the value of one of the `cls`'s members.
"""
if isinstance(value, cls):
return True
try:
return value in cls._value2member_map_
except TypeError:
return value in cls._unhashable_values_
def __delattr__(cls, attr):
# nicer error message when someone tries to delete an attribute
# (see issue19025).
if attr in cls._member_map_:
raise AttributeError("%r cannot delete member %r." % (cls.__name__, attr))
super().__delattr__(attr)
def __dir__(cls):
interesting = set([
'__class__', '__contains__', '__doc__', '__getitem__',
'__iter__', '__len__', '__members__', '__module__',
'__name__', '__qualname__',
]
+ cls._member_names_
)
if cls._new_member_ is not object.__new__:
interesting.add('__new__')
if cls.__init_subclass__ is not object.__init_subclass__:
interesting.add('__init_subclass__')
if cls._member_type_ is object:
return sorted(interesting)
else:
# return whatever mixed-in data type has
return sorted(set(dir(cls._member_type_)) | interesting)
def __getitem__(cls, name):
"""
Return the member matching `name`.
"""
return cls._member_map_[name]
def __iter__(cls):
"""
Return members in definition order.
"""
return (cls._member_map_[name] for name in cls._member_names_)
def __len__(cls):
"""
Return the number of members (no aliases)
"""
return len(cls._member_names_)
@bltns.property
def __members__(cls):
"""
Returns a mapping of member name->value.
This mapping lists all enum members, including aliases. Note that this
is a read-only view of the internal mapping.
"""
return MappingProxyType(cls._member_map_)
def __repr__(cls):
if Flag is not None and issubclass(cls, Flag):
return "<flag %r>" % cls.__name__
else:
return "<enum %r>" % cls.__name__
def __reversed__(cls):
"""
Return members in reverse definition order.
"""
return (cls._member_map_[name] for name in reversed(cls._member_names_))
def __setattr__(cls, name, value):
"""
Block attempts to reassign Enum members.
A simple assignment to the class namespace only changes one of the
several possible ways to get an Enum member from the Enum class,
resulting in an inconsistent Enumeration.
"""
member_map = cls.__dict__.get('_member_map_', {})
if name in member_map:
raise AttributeError('cannot reassign member %r' % (name, ))
super().__setattr__(name, value)
def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1, boundary=None):
"""
Convenience method to create a new Enum class.
`names` can be:
* A string containing member names, separated either with spaces or
commas. Values are incremented by 1 from `start`.
* An iterable of member names. Values are incremented by 1 from `start`.
* An iterable of (member name, value) pairs.
* A mapping of member name -> value pairs.
"""
metacls = cls.__class__
bases = (cls, ) if type is None else (type, cls)
_, first_enum = cls._get_mixins_(class_name, bases)
classdict = metacls.__prepare__(class_name, bases)
# special processing needed for names?
if isinstance(names, str):
names = names.replace(',', ' ').split()
if isinstance(names, (tuple, list)) and names and isinstance(names[0], str):
original_names, names = names, []
last_values = []
for count, name in enumerate(original_names):
value = first_enum._generate_next_value_(name, start, count, last_values[:])
last_values.append(value)
names.append((name, value))
if names is None:
names = ()
# Here, names is either an iterable of (name, value) or a mapping.
for item in names:
if isinstance(item, str):
member_name, member_value = item, names[item]
else:
member_name, member_value = item
classdict[member_name] = member_value
if module is None:
try:
module = sys._getframemodulename(2)
except AttributeError:
# Fall back on _getframe if _getframemodulename is missing
try:
module = sys._getframe(2).f_globals['__name__']
except (AttributeError, ValueError, KeyError):
pass
if module is None:
_make_class_unpicklable(classdict)
else:
classdict['__module__'] = module
if qualname is not None:
classdict['__qualname__'] = qualname
return metacls.__new__(metacls, class_name, bases, classdict, boundary=boundary)
def _convert_(cls, name, module, filter, source=None, *, boundary=None, as_global=False):
"""
Create a new Enum subclass that replaces a collection of global constants
"""
# convert all constants from source (or module) that pass filter() to
# a new Enum called name, and export the enum and its members back to
# module;
# also, replace the __reduce_ex__ method so unpickling works in
# previous Python versions
module_globals = sys.modules[module].__dict__
if source:
source = source.__dict__
else:
source = module_globals
# _value2member_map_ is populated in the same order every time
# for a consistent reverse mapping of number to name when there
# are multiple names for the same number.
members = [
(name, value)
for name, value in source.items()
if filter(name)]
try:
# sort by value
members.sort(key=lambda t: (t[1], t[0]))
except TypeError:
# unless some values aren't comparable, in which case sort by name
members.sort(key=lambda t: t[0])
body = {t[0]: t[1] for t in members}
body['__module__'] = module
tmp_cls = type(name, (object, ), body)
cls = _simple_enum(etype=cls, boundary=boundary or KEEP)(tmp_cls)
if as_global:
global_enum(cls)
else:
sys.modules[cls.__module__].__dict__.update(cls.__members__)
module_globals[name] = cls
return cls
@classmethod
def _check_for_existing_members_(mcls, class_name, bases):
for chain in bases:
for base in chain.__mro__:
if isinstance(base, EnumType) and base._member_names_:
raise TypeError(
"<enum %r> cannot extend %r"
% (class_name, base)
)
@classmethod
def _get_mixins_(mcls, class_name, bases):
"""
Returns the type for creating enum members, and the first inherited
enum class.
bases: the tuple of bases that was given to __new__
"""
if not bases:
return object, Enum
# ensure final parent class is an Enum derivative, find any concrete
# data type, and check that Enum has no members
first_enum = bases[-1]
if not isinstance(first_enum, EnumType):
raise TypeError("new enumerations should be created as "
"`EnumName([mixin_type, ...] [data_type,] enum_type)`")
member_type = mcls._find_data_type_(class_name, bases) or object
return member_type, first_enum
@classmethod
def _find_data_repr_(mcls, class_name, bases):
for chain in bases:
for base in chain.__mro__:
if base is object:
continue
elif isinstance(base, EnumType):
# if we hit an Enum, use it's _value_repr_
return base._value_repr_
elif '__repr__' in base.__dict__:
# this is our data repr
# double-check if a dataclass with a default __repr__
if (
'__dataclass_fields__' in base.__dict__
and '__dataclass_params__' in base.__dict__
and base.__dict__['__dataclass_params__'].repr
):
return _dataclass_repr
else:
return base.__dict__['__repr__']
return None
@classmethod
def _find_data_type_(mcls, class_name, bases):
# a datatype has a __new__ method, or a __dataclass_fields__ attribute
data_types = set()
base_chain = set()
for chain in bases:
candidate = None
for base in chain.__mro__:
base_chain.add(base)
if base is object:
continue
elif isinstance(base, EnumType):
if base._member_type_ is not object:
data_types.add(base._member_type_)
break
elif '__new__' in base.__dict__ or '__dataclass_fields__' in base.__dict__:
data_types.add(candidate or base)
break
else:
candidate = candidate or base
if len(data_types) > 1:
raise TypeError('too many data types for %r: %r' % (class_name, data_types))
elif data_types:
return data_types.pop()
else: