e657af35a1252ca5257333e5528b4c2b32aa46f0
[software/python-on-guile.git] / modules / language / python / module / enum.py
1 module(enum) ## needed in guile atm
2
3 import sys
4 from types import MappingProxyType, DynamicClassAttribute
5 from functools import reduce
6 from operator import or_ as _or_
7
8 # try _collections first to reduce startup cost
9 try:
10 from _collections import OrderedDict
11 except ImportError:
12 from collections import OrderedDict
13
14 __all__ = [
15 'EnumMeta',
16 'Enum', 'IntEnum', 'Flag', 'IntFlag',
17 'auto', 'unique',
18 ]
19
20
21 def _is_descriptor(obj):
22 """Returns True if obj is a descriptor, False otherwise."""
23 return (
24 hasattr(obj, '__get__') or
25 hasattr(obj, '__set__') or
26 hasattr(obj, '__delete__'))
27
28
29 def _is_dunder(name):
30 """Returns True if a __dunder__ name, False otherwise."""
31 return (name[:2] == name[-2:] == '__' and
32 name[2:3] != '_' and
33 name[-3:-2] != '_' and
34 len(name) > 4)
35
36
37 def _is_sunder(name):
38 """Returns True if a _sunder_ name, False otherwise."""
39 return (name[0] == name[-1] == '_' and
40 name[1:2] != '_' and
41 name[-2:-1] != '_' and
42 len(name) > 2)
43
44 def _make_class_unpicklable(cls):
45 """Make the given class un-picklable."""
46 def _break_on_call_reduce(self, proto):
47 raise TypeError('%r cannot be pickled' % self)
48 cls.__reduce_ex__ = _break_on_call_reduce
49 cls.__module__ = '<unknown>'
50
51 _auto_null = object()
52
53 class auto:
54 """
55 Instances are replaced with an appropriate value in Enum class suites.
56 """
57 value = _auto_null
58
59 class _EnumDict(dict):
60 """Track enum member order and ensure member names are not reused.
61
62 EnumMeta will use the names found in self._member_names as the
63 enumeration member names.
64
65 """
66 def __init__(self):
67 super().__init__()
68 self._member_names = []
69 self._last_values = []
70
71 def __setitem__(self, key, value):
72 """Changes anything not dundered or not a descriptor.
73
74 If an enum member name is used twice, an error is raised; duplicate
75 values are not checked for.
76
77 Single underscore (sunder) names are reserved.
78
79 """
80 if _is_sunder(key):
81 if key not in (
82 '_order_', '_create_pseudo_member_',
83 '_generate_next_value_', '_missing_',
84 ):
85 raise ValueError('_names_ are reserved for future Enum use')
86 if key == '_generate_next_value_':
87 setattr(self, '_generate_next_value', value)
88 elif _is_dunder(key):
89 if key == '__order__':
90 key = '_order_'
91 elif (key in self._member_names):
92 # descriptor overwriting an enum?
93 raise TypeError('Attempted to reuse key: %r' % key)
94 elif (not _is_descriptor(value)):
95 if key in self:
96 # enum overwriting a descriptor?
97 raise TypeError('%r already defined as: %r' % (key, self[key]))
98 if isinstance(value, auto):
99 if value.value == _auto_null:
100 value.value = self._generate_next_value(key, 1, len(self._member_names), self._last_values[:])
101 value = value.value
102 self._member_names.append(key)
103 self._last_values.append(value)
104 super().__setitem__(key, value)
105
106 # Dummy value for Enum as EnumMeta explicitly checks for it, but of course
107 # until EnumMeta finishes running the first time the Enum class doesn't exist.
108 # This is also why there are checks in EnumMeta like `if Enum is not None`
109 Enum = None
110
111 pk('EnumMeta')
112 class EnumMeta(type):
113 """Metaclass for Enum"""
114 @classmethod
115 def __prepare__(metacls, cls, bases):
116 # create the namespace dict
117 enum_dict = _EnumDict()
118
119 # inherit previous flags and _generate_next_value_ function
120 member_type, first_enum = metacls._get_mixins_(bases)
121
122 if first_enum is not None:
123 enum_dict['_generate_next_value_'] = getattr(first_enum, '_generate_next_value_', None)
124
125 return enum_dict
126
127 def __new__(metacls, cls, bases, classdict):
128 # an Enum class is final once enumeration items have been defined; it
129 # cannot be mixed with other types (int, float, etc.) if it has an
130 # inherited __new__ unless a new __new__ is defined (or the resulting
131 # class will fail).
132 pk('new',metacls,cls)
133 member_type, first_enum = metacls._get_mixins_(bases)
134
135 new, save_new, use_args = metacls._find_new_(classdict, member_type,
136 first_enum)
137 # save enum items into separate mapping so they don't get baked into
138 # the new class
139 enum_members = {k: classdict[k] for k in classdict._member_names}
140
141 for name in classdict._member_names:
142 del classdict[name]
143
144 # adjust the sunders
145 _order_ = classdict.pop('_order_', None)
146
147 # check for illegal enum names (any others?)
148 invalid_names = set(enum_members) & {'mro', }
149 if invalid_names:
150 raise ValueError('Invalid enum member name: {0}'.format(
151 ','.join(invalid_names)))
152
153 # create a default docstring if one has not been provided
154 if '__doc__' not in classdict:
155 classdict['__doc__'] = 'An enumeration.'
156
157 # create our new Enum type
158 enum_class = super().__new__(metacls, cls, bases, classdict)
159 enum_class._member_names_ = [] # names in definition order
160 enum_class._member_map_ = OrderedDict() # name->value map
161 enum_class._member_type_ = member_type
162
163 # save attributes from super classes so we know if we can take
164 # the shortcut of storing members in the class dict
165 base_attributes = {a for b in enum_class.mro() for a in b.__dict__}
166
167 # Reverse value->name map for hashable values.
168 enum_class._value2member_map_ = {}
169
170 # If a custom type is mixed into the Enum, and it does not know how
171 # to pickle itself, pickle.dumps will succeed but pickle.loads will
172 # fail. Rather than have the error show up later and possibly far
173 # from the source, sabotage the pickle protocol for this class so
174 # that pickle.dumps also fails.
175 #
176 # However, if the new class implements its own __reduce_ex__, do not
177 # sabotage -- it's on them to make sure it works correctly. We use
178 # __reduce_ex__ instead of any of the others as it is preferred by
179 # pickle over __reduce__, and it handles all pickle protocols.
180 if '__reduce_ex__' not in classdict:
181 if member_type is not object:
182 methods = ('__getnewargs_ex__', '__getnewargs__',
183 '__reduce_ex__', '__reduce__')
184 if not any(m in member_type.__dict__ for m in methods):
185 _make_class_unpicklable(enum_class)
186
187 # instantiate them, checking for duplicates as we go
188 # we instantiate first instead of checking for duplicates first in case
189 # a custom __new__ is doing something funky with the values -- such as
190 # auto-numbering ;)
191 for member_name in classdict._member_names:
192 value = enum_members[member_name]
193 if not isinstance(value, tuple):
194 args = (value, )
195 else:
196 args = value
197
198 if member_type is tuple: # special case for tuple enums
199 args = (args, ) # wrap it one more time
200
201 if not use_args:
202 enum_member = new(enum_class)
203 if not hasattr(enum_member, '_value_'):
204 enum_member._value_ = value
205 else:
206 enum_member = new(enum_class, *args)
207 if not hasattr(enum_member, '_value_'):
208 if member_type is object:
209 enum_member._value_ = value
210 else:
211 enum_member._value_ = member_type(*args)
212 value = enum_member._value_
213 enum_member._name_ = member_name
214 enum_member.__objclass__ = enum_class
215 enum_member.__init__(*args)
216
217 # If another member with the same value was already defined, the
218 # new member becomes an alias to the existing one.
219 for name, canonical_member in enum_class._member_map_.items():
220 if canonical_member._value_ == enum_member._value_:
221 enum_member = canonical_member
222 break
223 else:
224 # Aliases don't appear in member names (only in __members__).
225 enum_class._member_names_.append(member_name)
226
227 # performance boost for any member that would not shadow
228 # a DynamicClassAttribute
229 if member_name not in base_attributes:
230 setattr(enum_class, member_name, enum_member)
231 # now add to _member_map_
232
233 enum_class._member_map_[member_name] = enum_member
234 try:
235 # This may fail if value is not hashable. We can't add the value
236 # to the map, and by-value lookups for this value will be
237 # linear.
238 enum_class._value2member_map_[value] = enum_member
239 except TypeError:
240 pass
241
242 # double check that repr and friends are not the mixin's or various
243 # things break (such as pickle)
244 for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
245 class_method = getattr(enum_class, name)
246 obj_method = getattr(member_type, name, None)
247 enum_method = getattr(first_enum, name, None)
248 if obj_method is not None and obj_method is class_method:
249 setattr(enum_class, name, enum_method)
250
251 # replace any other __new__ with our own (as long as Enum is not None,
252 # anyway) -- again, this is to support pickle
253 if Enum is not None:
254 # if the user defined their own __new__, save it before it gets
255 # clobbered in case they subclass later
256 if save_new:
257 enum_class.__new_member__ = __new__
258 enum_class.__new__ = Enum.__new__
259
260 # py3 support for definition order (helps keep py2/py3 code in sync)
261 if _order_ is not None:
262 if isinstance(_order_, str):
263 _order_ = _order_.replace(',', ' ').split()
264 if _order_ != enum_class._member_names_:
265 raise TypeError('member order does not match _order_')
266
267 return enum_class
268
269 def __bool__(self):
270 """
271 classes/types should always be True.
272 """
273 return True
274
275 def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1):
276 """Either returns an existing member, or creates a new enum class.
277
278 This method is used both when an enum class is given a value to match
279 to an enumeration member (i.e. Color(3)) and for the functional API
280 (i.e. Color = Enum('Color', names='RED GREEN BLUE')).
281
282 When used for the functional API:
283
284 `value` will be the name of the new class.
285
286 `names` should be either a string of white-space/comma delimited names
287 (values will start at `start`), or an iterator/mapping of name, value pairs.
288
289 `module` should be set to the module this class is being created in;
290 if it is not set, an attempt to find that module will be made, but if
291 it fails the class will not be picklable.
292
293 `qualname` should be set to the actual location this class can be found
294 at in its module; by default it is set to the global scope. If this is
295 not correct, unpickling will fail in some circumstances.
296
297 `type`, if set, will be mixed in as the first base class.
298
299 """
300 if names is None: # simple value lookup
301 return cls.__new__(cls, value)
302 # otherwise, functional API: we're creating a new Enum type
303 return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)
304
305 def __contains__(cls, member):
306 return isinstance(member, cls) and member._name_ in cls._member_map_
307
308 def __delattr__(cls, attr):
309 # nicer error message when someone tries to delete an attribute
310 # (see issue19025).
311 if attr in cls._member_map_:
312 raise AttributeError(
313 "%s: cannot delete Enum member." % cls.__name__)
314 super().__delattr__(attr)
315
316 def __dir__(self):
317 return (['__class__', '__doc__', '__members__', '__module__'] +
318 self._member_names_)
319
320 def __getattr__(cls, name):
321 """Return the enum member matching `name`
322
323 We use __getattr__ instead of descriptors or inserting into the enum
324 class' __dict__ in order to support `name` and `value` being both
325 properties for enum members (which live in the class' __dict__) and
326 enum members themselves.
327
328 """
329 if _is_dunder(name):
330 raise AttributeError(name)
331 try:
332 return cls._member_map_[name]
333 except KeyError:
334 raise AttributeError(name) from None
335
336 def __getitem__(cls, name):
337 return cls._member_map_[name]
338
339 def __iter__(cls):
340 return (cls._member_map_[name] for name in cls._member_names_)
341
342 def __len__(cls):
343 return len(cls._member_names_)
344
345 @property
346 def __members__(cls):
347 """Returns a mapping of member name->value.
348
349 This mapping lists all enum members, including aliases. Note that this
350 is a read-only view of the internal mapping.
351
352 """
353 return MappingProxyType(cls._member_map_)
354
355 def __repr__(cls):
356 return "<enum %r>" % cls.__name__
357
358 def __reversed__(cls):
359 return (cls._member_map_[name] for name in reversed(cls._member_names_))
360
361 def __setattr__(cls, name, value):
362 """Block attempts to reassign Enum members.
363
364 A simple assignment to the class namespace only changes one of the
365 several possible ways to get an Enum member from the Enum class,
366 resulting in an inconsistent Enumeration.
367
368 """
369
370 member_map = cls.__dict__.get('_member_map_', {})
371
372 if name in member_map:
373 raise AttributeError('Cannot reassign members.')
374
375 super().__setattr__(name, value)
376
377
378 def _create_(cls, class_name, names=None, *, module=None, qualname=None, type=None, start=1):
379 """Convenience method to create a new Enum class.
380
381 `names` can be:
382
383 * A string containing member names, separated either with spaces or
384 commas. Values are incremented by 1 from `start`.
385 * An iterable of member names. Values are incremented by 1 from `start`.
386 * An iterable of (member name, value) pairs.
387 * A mapping of member name -> value pairs.
388
389 """
390 metacls = cls.__class__
391 bases = (cls, ) if type is None else (type, cls)
392 _, first_enum = cls._get_mixins_(bases)
393 classdict = metacls.__prepare__(class_name, bases)
394
395 # special processing needed for names?
396 if isinstance(names, str):
397 names = names.replace(',', ' ').split()
398 if isinstance(names, (tuple, list)) and names and isinstance(names[0], str):
399 original_names, names = names, []
400 last_values = []
401 for count, name in enumerate(original_names):
402 value = first_enum._generate_next_value_(name, start, count, last_values[:])
403 last_values.append(value)
404 names.append((name, value))
405
406 # Here, names is either an iterable of (name, value) or a mapping.
407 for item in names:
408 if isinstance(item, str):
409 member_name, member_value = item, names[item]
410 else:
411 member_name, member_value = item
412 classdict[member_name] = member_value
413 enum_class = metacls.__new__(metacls, class_name, bases, classdict)
414
415 # TODO: replace the frame hack if a blessed way to know the calling
416 # module is ever developed
417 if module is None:
418 try:
419 module = sys._getframe(2).f_globals['__name__']
420 except (AttributeError, ValueError) as exc:
421 pass
422 if module is None:
423 _make_class_unpicklable(enum_class)
424 else:
425 enum_class.__module__ = module
426 if qualname is not None:
427 enum_class.__qualname__ = qualname
428
429 return enum_class
430
431 @staticmethod
432 def _get_mixins_(bases):
433 """Returns the type for creating enum members, and the first inherited
434 enum class.
435
436 bases: the tuple of bases that was given to __new__
437
438 """
439
440 if not bases:
441 return object, Enum
442
443 # double check that we are not subclassing a class with existing
444 # enumeration members; while we're at it, see if any other data
445 # type has been mixed in so we can use the correct __new__
446 member_type = first_enum = None
447 for base in bases:
448 if (base is not Enum and
449 issubclass(base, Enum) and
450 base._member_names_):
451 raise TypeError("Cannot extend enumerations")
452
453 # base is now the last base in bases
454 if not issubclass(base, Enum):
455 raise TypeError("new enumerations must be created as "
456 "`ClassName([mixin_type,] enum_type)`")
457
458 # get correct mix-in type (either mix-in type of Enum subclass, or
459 # first base if last base is Enum)
460 if not issubclass(bases[0], Enum):
461 member_type = bases[0] # first data type
462 first_enum = bases[-1] # enum type
463 else:
464 for base in bases[0].__mro__:
465 # most common: (IntEnum, int, Enum, object)
466 # possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>,
467 # <class 'int'>, <Enum 'Enum'>,
468 # <class 'object'>)
469 if issubclass(base, Enum):
470 if first_enum is None:
471 first_enum = base
472 else:
473 if member_type is None:
474 member_type = base
475
476 return member_type, first_enum
477
478 @staticmethod
479 def _find_new_(classdict, member_type, first_enum):
480 """Returns the __new__ to be used for creating the enum members.
481
482 classdict: the class dictionary given to __new__
483 member_type: the data type whose __new__ will be used by default
484 first_enum: enumeration to check for an overriding __new__
485
486 """
487 # now find the correct __new__, checking to see of one was defined
488 # by the user; also check earlier enum classes in case a __new__ was
489 # saved as __new_member__
490
491 __new__ = classdict.get('__new__', None)
492
493 # should __new__ be saved as __new_member__ later?
494 save_new = __new__ is not None
495
496 if __new__ is None:
497 # check all possibles for __new_member__ before falling back to
498 # __new__
499 for method in ('__new_member__', '__new__'):
500 for possible in (member_type, first_enum):
501 target = getattr(possible, method, None)
502 if target not in {
503 None,
504 None.__new__,
505 object.__new__,
506 Enum.__new__,
507 }:
508 __new__ = target
509 break
510 if __new__ is not None:
511 break
512 else:
513 __new__ = object.__new__
514
515 # if a non-object.__new__ is used then whatever value/tuple was
516 # assigned to the enum member name will be passed to __new__ and to the
517 # new enum member's __init__
518 if __new__ is object.__new__:
519 use_args = False
520 else:
521 use_args = True
522
523 return __new__, save_new, use_args
524
525 pk('enum')
526
527 class Enum(metaclass=EnumMeta):
528 """Generic enumeration.
529
530 Derive from this class to define new enumerations.
531
532 """
533
534 def __new__(cls, value):
535 # all enum instances are actually created during class construction
536 # without calling this method; this method is called by the metaclass'
537 # __call__ (i.e. Color(3) ), and by pickle
538 if type(value) is cls:
539 # For lookups like Color(Color.RED)
540 return value
541 # by-value search for a matching enum member
542 # see if it's in the reverse mapping (for hashable values)
543 try:
544 if value in cls._value2member_map_:
545 return cls._value2member_map_[value]
546 except TypeError:
547 # not there, now do long search -- O(n) behavior
548 for member in cls._member_map_.values():
549 if member._value_ == value:
550 return member
551 # still not found -- try _missing_ hook
552 return cls._missing_(value)
553
554 def _generate_next_value_(name, start, count, last_values):
555 for last_value in reversed(last_values):
556 try:
557 return last_value + 1
558 except TypeError:
559 pass
560 else:
561 return start
562
563 @classmethod
564 def _missing_(cls, value):
565 raise ValueError("%r is not a valid %s" % (value, cls.__name__))
566
567 def __repr__(self):
568 return "<%s.%s: %r>" % (
569 self.__class__.__name__, self._name_, self._value_)
570
571 def __str__(self):
572 return "%s.%s" % (self.__class__.__name__, self._name_)
573
574 def __dir__(self):
575 added_behavior = [
576 m
577 for cls in self.__class__.mro()
578 for m in cls.__dict__
579 if m[0] != '_' and m not in self._member_map_
580 ]
581 return (['__class__', '__doc__', '__module__'] + added_behavior)
582
583 def __format__(self, format_spec):
584 # mixed-in Enums should use the mixed-in type's __format__, otherwise
585 # we can get strange results with the Enum name showing up instead of
586 # the value
587
588 # pure Enum branch
589 if self._member_type_ is object:
590 cls = str
591 val = str(self)
592 # mix-in branch
593 else:
594 cls = self._member_type_
595 val = self._value_
596 return cls.__format__(val, format_spec)
597
598 def __hash__(self):
599 return hash(self._name_)
600
601 def __reduce_ex__(self, proto):
602 return self.__class__, (self._value_, )
603
604 # DynamicClassAttribute is used to provide access to the `name` and
605 # `value` properties of enum members while keeping some measure of
606 # protection from modification, while still allowing for an enumeration
607 # to have members named `name` and `value`. This works because enumeration
608 # members are not set directly on the enum class -- __getattr__ is
609 # used to look them up.
610
611 @DynamicClassAttribute
612 def name(self):
613 """The name of the Enum member."""
614 return self._name_
615
616 @DynamicClassAttribute
617 def value(self):
618 """The value of the Enum member."""
619 return self._value_
620
621 @classmethod
622 def _convert(cls, name, module, filter, source=None):
623 """
624 Create a new Enum subclass that replaces a collection of global constants
625 """
626 # convert all constants from source (or module) that pass filter() to
627 # a new Enum called name, and export the enum and its members back to
628 # module;
629 # also, replace the __reduce_ex__ method so unpickling works in
630 # previous Python versions
631 module_globals = vars(sys.modules[module])
632 if source:
633 source = vars(source)
634 else:
635 source = module_globals
636 # We use an OrderedDict of sorted source keys so that the
637 # _value2member_map is populated in the same order every time
638 # for a consistent reverse mapping of number to name when there
639 # are multiple names for the same number rather than varying
640 # between runs due to hash randomization of the module dictionary.
641 members = [
642 (name, source[name])
643 for name in source.keys()
644 if filter(name)]
645 try:
646 # sort by value
647 members.sort(key=lambda t: (t[1], t[0]))
648 except TypeError:
649 # unless some values aren't comparable, in which case sort by name
650 members.sort(key=lambda t: t[0])
651 cls = cls(name, members, module=module)
652 cls.__reduce_ex__ = _reduce_ex_by_name
653 module_globals.update(cls.__members__)
654 module_globals[name] = cls
655 return cls
656
657 pk('intenum')
658
659 class IntEnum(int, Enum):
660 """Enum where members are also (and must be) ints"""
661
662
663 def _reduce_ex_by_name(self, proto):
664 return self.name
665
666 pk('flag')
667 class Flag(Enum):
668 """Support for flags"""
669
670 def _generate_next_value_(name, start, count, last_values):
671 """
672 Generate the next value when not given.
673
674 name: the name of the member
675 start: the initital start value or None
676 count: the number of existing members
677 last_value: the last value assigned or None
678 """
679 if not count:
680 return start if start is not None else 1
681 for last_value in reversed(last_values):
682 try:
683 high_bit = _high_bit(last_value)
684 break
685 except Exception:
686 raise TypeError('Invalid Flag value: %r' % last_value) from None
687 return 2 ** (high_bit+1)
688
689 @classmethod
690 def _missing_(cls, value):
691 original_value = value
692 if value < 0:
693 value = ~value
694 possible_member = cls._create_pseudo_member_(value)
695 if original_value < 0:
696 possible_member = ~possible_member
697 return possible_member
698
699 @classmethod
700 def _create_pseudo_member_(cls, value):
701 """
702 Create a composite member iff value contains only members.
703 """
704 pseudo_member = cls._value2member_map_.get(value, None)
705 if pseudo_member is None:
706 # verify all bits are accounted for
707 _, extra_flags = _decompose(cls, value)
708 if extra_flags:
709 raise ValueError("%r is not a valid %s" % (value, cls.__name__))
710 # construct a singleton enum pseudo-member
711 pseudo_member = object.__new__(cls)
712 pseudo_member._name_ = None
713 pseudo_member._value_ = value
714 # use setdefault in case another thread already created a composite
715 # with this value
716 pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member)
717 return pseudo_member
718
719 def __contains__(self, other):
720 if not isinstance(other, self.__class__):
721 return NotImplemented
722 return other._value_ & self._value_ == other._value_
723
724 def __repr__(self):
725 cls = self.__class__
726 if self._name_ is not None:
727 return '<%s.%s: %r>' % (cls.__name__, self._name_, self._value_)
728 members, uncovered = _decompose(cls, self._value_)
729 return '<%s.%s: %r>' % (
730 cls.__name__,
731 '|'.join([str(m._name_ or m._value_) for m in members]),
732 self._value_,
733 )
734
735 def __str__(self):
736 cls = self.__class__
737 if self._name_ is not None:
738 return '%s.%s' % (cls.__name__, self._name_)
739 members, uncovered = _decompose(cls, self._value_)
740 if len(members) == 1 and members[0]._name_ is None:
741 return '%s.%r' % (cls.__name__, members[0]._value_)
742 else:
743 return '%s.%s' % (
744 cls.__name__,
745 '|'.join([str(m._name_ or m._value_) for m in members]),
746 )
747
748 def __bool__(self):
749 return bool(self._value_)
750
751 def __or__(self, other):
752 if not isinstance(other, self.__class__):
753 return NotImplemented
754 return self.__class__(self._value_ | other._value_)
755
756 def __and__(self, other):
757 if not isinstance(other, self.__class__):
758 return NotImplemented
759 return self.__class__(self._value_ & other._value_)
760
761 def __xor__(self, other):
762 if not isinstance(other, self.__class__):
763 return NotImplemented
764 return self.__class__(self._value_ ^ other._value_)
765
766 def __invert__(self):
767 members, uncovered = _decompose(self.__class__, self._value_)
768 inverted_members = [
769 m for m in self.__class__
770 if m not in members and not m._value_ & self._value_
771 ]
772 inverted = reduce(_or_, inverted_members, self.__class__(0))
773 return self.__class__(inverted)
774
775 pk('intflag')
776 class IntFlag(int, Flag):
777 """Support for integer-based Flags"""
778
779 @classmethod
780 def _missing_(cls, value):
781 if not isinstance(value, int):
782 raise ValueError("%r is not a valid %s" % (value, cls.__name__))
783 new_member = cls._create_pseudo_member_(value)
784 return new_member
785
786 @classmethod
787 def _create_pseudo_member_(cls, value):
788 pseudo_member = cls._value2member_map_.get(value, None)
789 if pseudo_member is None:
790 need_to_create = [value]
791 # get unaccounted for bits
792 _, extra_flags = _decompose(cls, value)
793 # timer = 10
794 while extra_flags:
795 # timer -= 1
796 bit = _high_bit(extra_flags)
797 flag_value = 2 ** bit
798 if (flag_value not in cls._value2member_map_ and
799 flag_value not in need_to_create
800 ):
801 need_to_create.append(flag_value)
802 if extra_flags == -flag_value:
803 extra_flags = 0
804 else:
805 extra_flags ^= flag_value
806 for value in reversed(need_to_create):
807 # construct singleton pseudo-members
808 pseudo_member = int.__new__(cls, value)
809 pseudo_member._name_ = None
810 pseudo_member._value_ = value
811 # use setdefault in case another thread already created a composite
812 # with this value
813 pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member)
814 return pseudo_member
815
816 def __or__(self, other):
817 if not isinstance(other, (self.__class__, int)):
818 return NotImplemented
819 result = self.__class__(self._value_ | self.__class__(other)._value_)
820 return result
821
822 def __and__(self, other):
823 if not isinstance(other, (self.__class__, int)):
824 return NotImplemented
825 return self.__class__(self._value_ & self.__class__(other)._value_)
826
827 def __xor__(self, other):
828 if not isinstance(other, (self.__class__, int)):
829 return NotImplemented
830 return self.__class__(self._value_ ^ self.__class__(other)._value_)
831
832 __ror__ = __or__
833 __rand__ = __and__
834 __rxor__ = __xor__
835
836 def __invert__(self):
837 result = self.__class__(~self._value_)
838 return result
839
840 pk('rest')
841
842 def _high_bit(value):
843 """returns index of highest bit, or -1 if value is zero or negative"""
844 return value.bit_length() - 1
845
846 def unique(enumeration):
847 """Class decorator for enumerations ensuring unique member values."""
848 duplicates = []
849 for name, member in enumeration.__members__.items():
850 if name != member.name:
851 duplicates.append((name, member.name))
852 if duplicates:
853 alias_details = ', '.join(
854 ["%s -> %s" % (alias, name) for (alias, name) in duplicates])
855 raise ValueError('duplicate values found in %r: %s' %
856 (enumeration, alias_details))
857 return enumeration
858
859 def _decompose(flag, value):
860 """Extract all members from the value."""
861 # _decompose is only called if the value is not named
862 not_covered = value
863 negative = value < 0
864 # issue29167: wrap accesses to _value2member_map_ in a list to avoid race
865 # conditions between iterating over it and having more psuedo-
866 # members added to it
867 if negative:
868 # only check for named flags
869 flags_to_check = [
870 (m, v)
871 for v, m in list(flag._value2member_map_.items())
872 if m.name is not None
873 ]
874 else:
875 # check for named flags and powers-of-two flags
876 flags_to_check = [
877 (m, v)
878 for v, m in list(flag._value2member_map_.items())
879 if m.name is not None or _power_of_two(v)
880 ]
881 members = []
882 for member, member_value in flags_to_check:
883 if member_value and member_value & value == member_value:
884 members.append(member)
885 not_covered &= ~member_value
886 if not members and value in flag._value2member_map_:
887 members.append(flag._value2member_map_[value])
888 members.sort(key=lambda m: m._value_, reverse=True)
889 if len(members) > 1 and members[0].value == value:
890 # we have the breakdown, don't need the value member itself
891 members.pop(0)
892 return members, not_covered
893
894 def _power_of_two(value):
895 if value < 1:
896 return False
897 return value == 2 ** _high_bit(value)