enum.py 34 KB

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