Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathenum.py
More file actions
Latest commit
877 lines (744 loc) · 32.8 KB
/
Copy pathenum.py
File metadata and controls
877 lines (744 loc) · 32.8 KB
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
importsys
fromtypesimportMappingProxyType, DynamicClassAttribute
fromfunctoolsimportreduce
fromoperatorimportor_as_or_
# try _collections first to reduce startup cost
try:
from_collectionsimportOrderedDict
exceptImportError:
fromcollectionsimportOrderedDict
__all__= [
'EnumMeta',
'Enum', 'IntEnum', 'Flag', 'IntFlag',
'auto', 'unique',
]
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 (name[:2] ==name[-2:] =='__'and
name[2:3] !='_'and
name[-3:-2] !='_'and
len(name) >4)
def_is_sunder(name):
"""Returns True if a _sunder_ name, False otherwise."""
return (name[0] ==name[-1] =='_'and
name[1:2] !='_'and
name[-2:-1] !='_'and
len(name) >2)
def_make_class_unpicklable(cls):
"""Make the given class un-picklable."""
def_break_on_call_reduce(self, proto):
raiseTypeError('%r cannot be pickled'%self)
cls.__reduce_ex__=_break_on_call_reduce
cls.__module__='<unknown>'
_auto_null=object()
classauto:
"""
Instances are replaced with an appropriate value in Enum class suites.
"""
value=_auto_null
class_EnumDict(dict):
"""Track enum member order and ensure member names are not reused.
EnumMeta will use the names found in self._member_names as the
enumeration member names.
"""
def__init__(self):
super().__init__()
self._member_names= []
self._last_values= []
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_sunder(key):
ifkeynotin (
'_order_', '_create_pseudo_member_',
'_generate_next_value_', '_missing_',
):
raiseValueError('_names_ are reserved for future Enum use')
ifkey=='_generate_next_value_':
setattr(self, '_generate_next_value', value)
elif_is_dunder(key):
ifkey=='__order__':
key='_order_'
elifkeyinself._member_names:
# descriptor overwriting an enum?
raiseTypeError('Attempted to reuse key: %r'%key)
elifnot_is_descriptor(value):
ifkeyinself:
# enum overwriting a descriptor?
raiseTypeError('%r already defined as: %r'% (key, self[key]))
ifisinstance(value, auto):
ifvalue.value==_auto_null:
value.value=self._generate_next_value(key, 1, len(self._member_names), self._last_values[:])
value=value.value
self._member_names.append(key)
self._last_values.append(value)
super().__setitem__(key, value)
# Dummy value for Enum as EnumMeta explicitly checks for it, but of course
# until EnumMeta finishes running the first time the Enum class doesn't exist.
# This is also why there are checks in EnumMeta like `if Enum is not None`
Enum=None
classEnumMeta(type):
"""Metaclass for Enum"""
@classmethod
def__prepare__(metacls, cls, bases):
# create the namespace dict
enum_dict=_EnumDict()
# inherit previous flags and _generate_next_value_ function
member_type, first_enum=metacls._get_mixins_(bases)
iffirst_enumisnotNone:
enum_dict['_generate_next_value_'] =getattr(first_enum, '_generate_next_value_', None)
returnenum_dict
def__new__(metacls, cls, bases, classdict):
# 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).
member_type, first_enum=metacls._get_mixins_(bases)
__new__, save_new, use_args=metacls._find_new_(classdict, member_type,
first_enum)
# save enum items into separate mapping so they don't get baked into
# the new class
enum_members= {k: classdict[k] forkinclassdict._member_names}
fornameinclassdict._member_names:
delclassdict[name]
# adjust the sunders
_order_=classdict.pop('_order_', None)
# check for illegal enum names (any others?)
invalid_names=set(enum_members) & {'mro', }
ifinvalid_names:
raiseValueError('Invalid enum member name: {0}'.format(
','.join(invalid_names)))
# create a default docstring if one has not been provided
if'__doc__'notinclassdict:
classdict['__doc__'] ='An enumeration.'
# create our new Enum type
enum_class=super().__new__(metacls, cls, bases, classdict)
enum_class._member_names_= [] # names in definition order
enum_class._member_map_=OrderedDict() # name->value map
enum_class._member_type_=member_type
# save DynamicClassAttribute attributes from super classes so we know
# if we can take the shortcut of storing members in the class dict
dynamic_attributes= {kforcinenum_class.mro()
fork, vinc.__dict__.items()
ifisinstance(v, DynamicClassAttribute)}
# Reverse value->name map for hashable values.
enum_class._value2member_map_= {}
# If a custom type is mixed into the Enum, and it does not know how
# to pickle itself, pickle.dumps will succeed but pickle.loads will
# fail. Rather than have the error show up later and possibly far
# from the source, sabotage the pickle protocol for this class so
# that pickle.dumps also fails.
#
# However, if the new class implements its own __reduce_ex__, do not
# sabotage -- it's on them to make sure it works correctly. We use
# __reduce_ex__ instead of any of the others as it is preferred by
# pickle over __reduce__, and it handles all pickle protocols.
if'__reduce_ex__'notinclassdict:
ifmember_typeisnotobject:
methods= ('__getnewargs_ex__', '__getnewargs__',
'__reduce_ex__', '__reduce__')
ifnotany(minmember_type.__dict__forminmethods):
_make_class_unpicklable(enum_class)
# instantiate them, checking for duplicates as we go
# we instantiate first instead of checking for duplicates first in case
# a custom __new__ is doing something funky with the values -- such as
# auto-numbering ;)
formember_nameinclassdict._member_names:
value=enum_members[member_name]
ifnotisinstance(value, tuple):
args= (value, )
else:
args=value
ifmember_typeistuple: # special case for tuple enums
args= (args, ) # wrap it one more time
ifnotuse_args:
enum_member=__new__(enum_class)
ifnothasattr(enum_member, '_value_'):
enum_member._value_=value
else:
enum_member=__new__(enum_class, *args)
ifnothasattr(enum_member, '_value_'):
ifmember_typeisobject:
enum_member._value_=value
else:
enum_member._value_=member_type(*args)
value=enum_member._value_
enum_member._name_=member_name
enum_member.__objclass__=enum_class
enum_member.__init__(*args)
# If another member with the same value was already defined, the
# new member becomes an alias to the existing one.
forname, canonical_memberinenum_class._member_map_.items():
ifcanonical_member._value_==enum_member._value_:
enum_member=canonical_member
break
else:
# Aliases don't appear in member names (only in __members__).
enum_class._member_names_.append(member_name)
# performance boost for any member that would not shadow
# a DynamicClassAttribute
ifmember_namenotindynamic_attributes:
setattr(enum_class, member_name, enum_member)
# now add to _member_map_
enum_class._member_map_[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_[value] =enum_member
exceptTypeError:
pass
# double check that repr and friends are not the mixin's or various
# things break (such as pickle)
fornamein ('__repr__', '__str__', '__format__', '__reduce_ex__'):
class_method=getattr(enum_class, name)
obj_method=getattr(member_type, name, None)
enum_method=getattr(first_enum, name, None)
ifobj_methodisnotNoneandobj_methodisclass_method:
setattr(enum_class, name, enum_method)
# replace any other __new__ with our own (as long as Enum is not None,
# anyway) -- again, this is to support pickle
ifEnumisnotNone:
# if the user defined their own __new__, save it before it gets
# clobbered in case they subclass later
ifsave_new:
enum_class.__new_member__=__new__
enum_class.__new__=Enum.__new__
# py3 support for definition order (helps keep py2/py3 code in sync)
if_order_isnotNone:
ifisinstance(_order_, str):
_order_=_order_.replace(',', ' ').split()
if_order_!=enum_class._member_names_:
raiseTypeError('member order does not match _order_')
returnenum_class
def__bool__(self):
"""
classes/types should always be True.
"""
returnTrue
def__call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1):
"""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')).
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.
"""
ifnamesisNone: # simple value lookup
returncls.__new__(cls, value)
# otherwise, functional API: we're creating a new Enum type
returncls._create_(value, names, module=module, qualname=qualname, type=type, start=start)
def__contains__(cls, member):
returnisinstance(member, cls) andmember._name_incls._member_map_
def__delattr__(cls, attr):
# nicer error message when someone tries to delete an attribute
# (see issue19025).
ifattrincls._member_map_:
raiseAttributeError(
"%s: cannot delete Enum member."%cls.__name__)
super().__delattr__(attr)
def__dir__(self):
return (['__class__', '__doc__', '__members__', '__module__'] +
self._member_names_)
def__getattr__(cls, name):
"""Return the enum member matching `name`
We use __getattr__ instead of descriptors or inserting into the enum
class' __dict__ in order to support `name` and `value` being both
properties for enum members (which live in the class' __dict__) and
enum members themselves.
"""
if_is_dunder(name):
raiseAttributeError(name)
try:
returncls._member_map_[name]
exceptKeyError:
raiseAttributeError(name) fromNone
def__getitem__(cls, name):
returncls._member_map_[name]
def__iter__(cls):
return (cls._member_map_[name] fornameincls._member_names_)
def__len__(cls):
returnlen(cls._member_names_)
@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.
"""
returnMappingProxyType(cls._member_map_)
def__repr__(cls):
return"<enum %r>"%cls.__name__
def__reversed__(cls):
return (cls._member_map_[name] fornameinreversed(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_', {})
ifnameinmember_map:
raiseAttributeError('Cannot reassign members.')
super().__setattr__(name, value)
def_create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1):
"""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, ) iftypeisNoneelse (type, cls)
_, first_enum=cls._get_mixins_(bases)
classdict=metacls.__prepare__(class_name, bases)
# special processing needed for names?
ifisinstance(names, str):
names=names.replace(',', ' ').split()
ifisinstance(names, (tuple, list)) andnamesandisinstance(names[0], str):
original_names, names=names, []
last_values= []
forcount, nameinenumerate(original_names):
value=first_enum._generate_next_value_(name, start, count, last_values[:])
last_values.append(value)
names.append((name, value))
# Here, names is either an iterable of (name, value) or a mapping.
foriteminnames:
ifisinstance(item, str):
member_name, member_value=item, names[item]
else:
member_name, member_value=item
classdict[member_name] =member_value
enum_class=metacls.__new__(metacls, class_name, bases, classdict)
# TODO: replace the frame hack if a blessed way to know the calling
# module is ever developed
ifmoduleisNone:
try:
module=sys._getframe(2).f_globals['__name__']
except (AttributeError, ValueError) asexc:
pass
ifmoduleisNone:
_make_class_unpicklable(enum_class)
else:
enum_class.__module__=module
ifqualnameisnotNone:
enum_class.__qualname__=qualname
returnenum_class
@staticmethod
def_get_mixins_(bases):
"""Returns the type for creating enum members, and the first inherited
enum class.
bases: the tuple of bases that was given to __new__
"""
ifnotbases:
returnobject, Enum
# double check that we are not subclassing a class with existing
# enumeration members; while we're at it, see if any other data
# type has been mixed in so we can use the correct __new__
member_type=first_enum=None
forbaseinbases:
if (baseisnotEnumand
issubclass(base, Enum) and
base._member_names_):
raiseTypeError("Cannot extend enumerations")
# base is now the last base in bases
ifnotissubclass(base, Enum):
raiseTypeError("new enumerations must be created as "
"`ClassName([mixin_type,] enum_type)`")
# get correct mix-in type (either mix-in type of Enum subclass, or
# first base if last base is Enum)
ifnotissubclass(bases[0], Enum):
member_type=bases[0] # first data type
first_enum=bases[-1] # enum type
else:
forbaseinbases[0].__mro__:
# most common: (IntEnum, int, Enum, object)
# possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,
# <class 'int'>, <Enum 'Enum'>,
# <class 'object'>)
ifissubclass(base, Enum):
iffirst_enumisNone:
first_enum=base
else:
ifmember_typeisNone:
member_type=base
returnmember_type, first_enum
@staticmethod
def_find_new_(classdict, member_type, first_enum):
"""Returns the __new__ to be used for creating the enum members.
classdict: the class dictionary given to __new__
member_type: the data type whose __new__ will be used by default
first_enum: enumeration to check for an overriding __new__
"""
# now find the correct __new__, checking to see of one was defined
# by the user; also check earlier enum classes in case a __new__ was
# saved as __new_member__
__new__=classdict.get('__new__', None)
# should __new__ be saved as __new_member__ later?
save_new=__new__isnotNone
if__new__isNone:
# check all possibles for __new_member__ before falling back to
# __new__
formethodin ('__new_member__', '__new__'):
forpossiblein (member_type, first_enum):
target=getattr(possible, method, None)
iftargetnotin {
None,
None.__new__,
object.__new__,
Enum.__new__,
}:
__new__=target
break
if__new__isnotNone:
break
else:
__new__=object.__new__
# if a non-object.__new__ is used then whatever value/tuple was
# assigned to the enum member name will be passed to __new__ and to the
# new enum member's __init__
if__new__isobject.__new__:
use_args=False
else:
use_args=True
return__new__, save_new, use_args
classEnum(metaclass=EnumMeta):
"""Generic enumeration.
Derive from this class to define new enumerations.
"""
def__new__(cls, value):
# all enum instances are actually created during class construction
# without calling this method; this method is called by the metaclass'
# __call__ (i.e. Color(3) ), and by pickle
iftype(value) iscls:
# For lookups like Color(Color.RED)
returnvalue
# by-value search for a matching enum member
# see if it's in the reverse mapping (for hashable values)
try:
ifvalueincls._value2member_map_:
returncls._value2member_map_[value]
exceptTypeError:
# not there, now do long search -- O(n) behavior
formemberincls._member_map_.values():
ifmember._value_==value:
returnmember
# still not found -- try _missing_ hook
returncls._missing_(value)
def_generate_next_value_(name, start, count, last_values):
forlast_valueinreversed(last_values):
try:
returnlast_value+1
exceptTypeError:
pass
else:
returnstart
@classmethod
def_missing_(cls, value):
raiseValueError("%r is not a valid %s"% (value, cls.__name__))
def__repr__(self):
return"<%s.%s: %r>"% (
self.__class__.__name__, self._name_, self._value_)
def__str__(self):
return"%s.%s"% (self.__class__.__name__, self._name_)
def__dir__(self):
added_behavior= [
m
forclsinself.__class__.mro()
formincls.__dict__
ifm[0] !='_'andmnotinself._member_map_
]
return (['__class__', '__doc__', '__module__'] +added_behavior)
def__format__(self, format_spec):
# mixed-in Enums should use the mixed-in type's __format__, otherwise
# we can get strange results with the Enum name showing up instead of
# the value
# pure Enum branch
ifself._member_type_isobject:
cls=str
val=str(self)
# mix-in branch
else:
cls=self._member_type_
val=self._value_
returncls.__format__(val, format_spec)
def__hash__(self):
returnhash(self._name_)
def__reduce_ex__(self, proto):
returnself.__class__, (self._value_, )
# DynamicClassAttribute is used to provide access to the `name` and
# `value` properties of enum members while keeping some measure of
# protection from modification, while still allowing for an enumeration
# to have members named `name` and `value`. This works because enumeration
# members are not set directly on the enum class -- __getattr__ is
# used to look them up.
@DynamicClassAttribute
defname(self):
"""The name of the Enum member."""
returnself._name_
@DynamicClassAttribute
defvalue(self):
"""The value of the Enum member."""
returnself._value_
@classmethod
def_convert(cls, name, module, filter, source=None):
"""
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=vars(sys.modules[module])
ifsource:
source=vars(source)
else:
source=module_globals
# We use an OrderedDict of sorted source keys so that the
# _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 rather than varying
# between runs due to hash randomization of the module dictionary.
members= [
(name, source[name])
fornameinsource.keys()
iffilter(name)]
try:
# sort by value
members.sort(key=lambdat: (t[1], t[0]))
exceptTypeError:
# unless some values aren't comparable, in which case sort by name
members.sort(key=lambdat: t[0])
cls=cls(name, members, module=module)
cls.__reduce_ex__=_reduce_ex_by_name
module_globals.update(cls.__members__)
module_globals[name] =cls
returncls
classIntEnum(int, Enum):
"""Enum where members are also (and must be) ints"""
def_reduce_ex_by_name(self, proto):
returnself.name
classFlag(Enum):
"""Support for flags"""
def_generate_next_value_(name, start, count, last_values):
"""
Generate the next value when not given.
name: the name of the member
start: the initital start value or None
count: the number of existing members
last_value: the last value assigned or None
"""
ifnotcount:
returnstartifstartisnotNoneelse1
forlast_valueinreversed(last_values):
try:
high_bit=_high_bit(last_value)
break
exceptException:
raiseTypeError('Invalid Flag value: %r'%last_value) fromNone
return2** (high_bit+1)
@classmethod
def_missing_(cls, value):
original_value=value
ifvalue<0:
value=~value
possible_member=cls._create_pseudo_member_(value)
iforiginal_value<0:
possible_member=~possible_member
returnpossible_member
@classmethod
def_create_pseudo_member_(cls, value):
"""
Create a composite member iff value contains only members.
"""
pseudo_member=cls._value2member_map_.get(value, None)
ifpseudo_memberisNone:
# verify all bits are accounted for
_, extra_flags=_decompose(cls, value)
ifextra_flags:
raiseValueError("%r is not a valid %s"% (value, cls.__name__))
# construct a singleton enum pseudo-member
pseudo_member=object.__new__(cls)
pseudo_member._name_=None
pseudo_member._value_=value
# use setdefault in case another thread already created a composite
# with this value
pseudo_member=cls._value2member_map_.setdefault(value, pseudo_member)
returnpseudo_member
def__contains__(self, other):
ifnotisinstance(other, self.__class__):
returnNotImplemented
returnother._value_&self._value_==other._value_
def__repr__(self):
cls=self.__class__
ifself._name_isnotNone:
return'<%s.%s: %r>'% (cls.__name__, self._name_, self._value_)
members, uncovered=_decompose(cls, self._value_)
return'<%s.%s: %r>'% (
cls.__name__,
'|'.join([str(m._name_orm._value_) forminmembers]),
self._value_,
)
def__str__(self):
cls=self.__class__
ifself._name_isnotNone:
return'%s.%s'% (cls.__name__, self._name_)
members, uncovered=_decompose(cls, self._value_)
iflen(members) ==1andmembers[0]._name_isNone:
return'%s.%r'% (cls.__name__, members[0]._value_)
else:
return'%s.%s'% (
cls.__name__,
'|'.join([str(m._name_orm._value_) forminmembers]),
)
def__bool__(self):
returnbool(self._value_)
def__or__(self, other):
ifnotisinstance(other, self.__class__):
returnNotImplemented
returnself.__class__(self._value_|other._value_)
def__and__(self, other):
ifnotisinstance(other, self.__class__):
returnNotImplemented
returnself.__class__(self._value_&other._value_)
def__xor__(self, other):
ifnotisinstance(other, self.__class__):
returnNotImplemented
returnself.__class__(self._value_^other._value_)
def__invert__(self):
members, uncovered=_decompose(self.__class__, self._value_)
inverted_members= [
mforminself.__class__
ifmnotinmembersandnotm._value_&self._value_
]
inverted=reduce(_or_, inverted_members, self.__class__(0))
returnself.__class__(inverted)
classIntFlag(int, Flag):
"""Support for integer-based Flags"""
@classmethod
def_missing_(cls, value):
ifnotisinstance(value, int):
raiseValueError("%r is not a valid %s"% (value, cls.__name__))
new_member=cls._create_pseudo_member_(value)
returnnew_member
@classmethod
def_create_pseudo_member_(cls, value):
pseudo_member=cls._value2member_map_.get(value, None)
ifpseudo_memberisNone:
need_to_create= [value]
# get unaccounted for bits
_, extra_flags=_decompose(cls, value)
# timer = 10
whileextra_flags:
# timer -= 1
bit=_high_bit(extra_flags)
flag_value=2**bit
if (flag_valuenotincls._value2member_map_and
flag_valuenotinneed_to_create
):
need_to_create.append(flag_value)
ifextra_flags==-flag_value:
extra_flags=0
else:
extra_flags^=flag_value
forvalueinreversed(need_to_create):
# construct singleton pseudo-members
pseudo_member=int.__new__(cls, value)
pseudo_member._name_=None
pseudo_member._value_=value
# use setdefault in case another thread already created a composite
# with this value
pseudo_member=cls._value2member_map_.setdefault(value, pseudo_member)
returnpseudo_member
def__or__(self, other):
ifnotisinstance(other, (self.__class__, int)):
returnNotImplemented
result=self.__class__(self._value_|self.__class__(other)._value_)
returnresult
def__and__(self, other):
ifnotisinstance(other, (self.__class__, int)):
returnNotImplemented
returnself.__class__(self._value_&self.__class__(other)._value_)
def__xor__(self, other):
ifnotisinstance(other, (self.__class__, int)):
returnNotImplemented
returnself.__class__(self._value_^self.__class__(other)._value_)
__ror__=__or__
__rand__=__and__
__rxor__=__xor__
def__invert__(self):
result=self.__class__(~self._value_)
returnresult
def_high_bit(value):
"""returns index of highest bit, or -1 if value is zero or negative"""
returnvalue.bit_length() -1
defunique(enumeration):
"""Class decorator for enumerations ensuring unique member values."""
duplicates= []
forname, memberinenumeration.__members__.items():
ifname!=member.name:
duplicates.append((name, member.name))
ifduplicates:
alias_details=', '.join(
["%s -> %s"% (alias, name) for (alias, name) induplicates])
raiseValueError('duplicate values found in %r: %s'%
(enumeration, alias_details))
returnenumeration
def_decompose(flag, value):
"""Extract all members from the value."""
# _decompose is only called if the value is not named
not_covered=value
negative=value<0
# issue29167: wrap accesses to _value2member_map_ in a list to avoid race
# conditions between iterating over it and having more psuedo-
# members added to it
ifnegative:
# only check for named flags
flags_to_check= [
(m, v)
forv, minlist(flag._value2member_map_.items())
ifm.nameisnotNone
]
else:
# check for named flags and powers-of-two flags
flags_to_check= [
(m, v)
forv, minlist(flag._value2member_map_.items())
ifm.nameisnotNoneor_power_of_two(v)
]
members= []
formember, member_valueinflags_to_check:
ifmember_valueandmember_value&value==member_value:
members.append(member)
not_covered&=~member_value
ifnotmembersandvalueinflag._value2member_map_:
members.append(flag._value2member_map_[value])
members.sort(key=lambdam: m._value_, reverse=True)
iflen(members) >1andmembers[0].value==value:
# we have the breakdown, don't need the value member itself
members.pop(0)
returnmembers, not_covered
def_power_of_two(value):
ifvalue<1:
returnFalse
returnvalue==2**_high_bit(value)