enum.py 34 KB

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