enum.py 39 KB

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