enum.py 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  1. import sys
  2. import builtins as bltns
  3. from types import MappingProxyType, DynamicClassAttribute
  4. from operator import or_ as _or_
  5. from functools import reduce
  6. __all__ = [
  7. 'EnumType', 'EnumMeta',
  8. 'Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag', 'ReprEnum',
  9. 'auto', 'unique', 'property', 'verify', 'member', 'nonmember',
  10. 'FlagBoundary', 'STRICT', 'CONFORM', 'EJECT', 'KEEP',
  11. 'global_flag_repr', 'global_enum_repr', 'global_str', 'global_enum',
  12. 'EnumCheck', 'CONTINUOUS', 'NAMED_FLAGS', 'UNIQUE',
  13. 'pickle_by_global_name', 'pickle_by_enum_name',
  14. ]
  15. # Dummy value for Enum and Flag as there are explicit checks for them
  16. # before they have been created.
  17. # This is also why there are checks in EnumType like `if Enum is not None`
  18. Enum = Flag = EJECT = _stdlib_enums = ReprEnum = None
  19. class nonmember(object):
  20. """
  21. Protects item from becoming an Enum member during class creation.
  22. """
  23. def __init__(self, value):
  24. self.value = value
  25. class member(object):
  26. """
  27. Forces item to become an Enum member during class creation.
  28. """
  29. def __init__(self, value):
  30. self.value = value
  31. def _is_descriptor(obj):
  32. """
  33. Returns True if obj is a descriptor, False otherwise.
  34. """
  35. return (
  36. hasattr(obj, '__get__') or
  37. hasattr(obj, '__set__') or
  38. hasattr(obj, '__delete__')
  39. )
  40. def _is_dunder(name):
  41. """
  42. Returns True if a __dunder__ name, False otherwise.
  43. """
  44. return (
  45. len(name) > 4 and
  46. name[:2] == name[-2:] == '__' and
  47. name[2] != '_' and
  48. name[-3] != '_'
  49. )
  50. def _is_sunder(name):
  51. """
  52. Returns True if a _sunder_ name, False otherwise.
  53. """
  54. return (
  55. len(name) > 2 and
  56. name[0] == name[-1] == '_' and
  57. name[1:2] != '_' and
  58. name[-2:-1] != '_'
  59. )
  60. def _is_internal_class(cls_name, obj):
  61. # do not use `re` as `re` imports `enum`
  62. if not isinstance(obj, type):
  63. return False
  64. qualname = getattr(obj, '__qualname__', '')
  65. s_pattern = cls_name + '.' + getattr(obj, '__name__', '')
  66. e_pattern = '.' + s_pattern
  67. return qualname == s_pattern or qualname.endswith(e_pattern)
  68. def _is_private(cls_name, name):
  69. # do not use `re` as `re` imports `enum`
  70. pattern = '_%s__' % (cls_name, )
  71. pat_len = len(pattern)
  72. if (
  73. len(name) > pat_len
  74. and name.startswith(pattern)
  75. and name[pat_len:pat_len+1] != ['_']
  76. and (name[-1] != '_' or name[-2] != '_')
  77. ):
  78. return True
  79. else:
  80. return False
  81. def _is_single_bit(num):
  82. """
  83. True if only one bit set in num (should be an int)
  84. """
  85. if num == 0:
  86. return False
  87. num &= num - 1
  88. return num == 0
  89. def _make_class_unpicklable(obj):
  90. """
  91. Make the given obj un-picklable.
  92. obj should be either a dictionary, or an Enum
  93. """
  94. def _break_on_call_reduce(self, proto):
  95. raise TypeError('%r cannot be pickled' % self)
  96. if isinstance(obj, dict):
  97. obj['__reduce_ex__'] = _break_on_call_reduce
  98. obj['__module__'] = '<unknown>'
  99. else:
  100. setattr(obj, '__reduce_ex__', _break_on_call_reduce)
  101. setattr(obj, '__module__', '<unknown>')
  102. def _iter_bits_lsb(num):
  103. # num must be a positive integer
  104. original = num
  105. if isinstance(num, Enum):
  106. num = num.value
  107. if num < 0:
  108. raise ValueError('%r is not a positive integer' % original)
  109. while num:
  110. b = num & (~num + 1)
  111. yield b
  112. num ^= b
  113. def show_flag_values(value):
  114. return list(_iter_bits_lsb(value))
  115. def bin(num, max_bits=None):
  116. """
  117. Like built-in bin(), except negative values are represented in
  118. twos-compliment, and the leading bit always indicates sign
  119. (0=positive, 1=negative).
  120. >>> bin(10)
  121. '0b0 1010'
  122. >>> bin(~10) # ~10 is -11
  123. '0b1 0101'
  124. """
  125. ceiling = 2 ** (num).bit_length()
  126. if num >= 0:
  127. s = bltns.bin(num + ceiling).replace('1', '0', 1)
  128. else:
  129. s = bltns.bin(~num ^ (ceiling - 1) + ceiling)
  130. sign = s[:3]
  131. digits = s[3:]
  132. if max_bits is not None:
  133. if len(digits) < max_bits:
  134. digits = (sign[-1] * max_bits + digits)[-max_bits:]
  135. return "%s %s" % (sign, digits)
  136. def _dedent(text):
  137. """
  138. Like textwrap.dedent. Rewritten because we cannot import textwrap.
  139. """
  140. lines = text.split('\n')
  141. blanks = 0
  142. for i, ch in enumerate(lines[0]):
  143. if ch != ' ':
  144. break
  145. for j, l in enumerate(lines):
  146. lines[j] = l[i:]
  147. return '\n'.join(lines)
  148. class _not_given:
  149. def __repr__(self):
  150. return('<not given>')
  151. _not_given = _not_given()
  152. class _auto_null:
  153. def __repr__(self):
  154. return '_auto_null'
  155. _auto_null = _auto_null()
  156. class auto:
  157. """
  158. Instances are replaced with an appropriate value in Enum class suites.
  159. """
  160. def __init__(self, value=_auto_null):
  161. self.value = value
  162. def __repr__(self):
  163. return "auto(%r)" % self.value
  164. class property(DynamicClassAttribute):
  165. """
  166. This is a descriptor, used to define attributes that act differently
  167. when accessed through an enum member and through an enum class.
  168. Instance access is the same as property(), but access to an attribute
  169. through the enum class will instead look in the class' _member_map_ for
  170. a corresponding enum member.
  171. """
  172. member = None
  173. _attr_type = None
  174. _cls_type = None
  175. def __get__(self, instance, ownerclass=None):
  176. if instance is None:
  177. if self.member is not None:
  178. return self.member
  179. else:
  180. raise AttributeError(
  181. '%r has no attribute %r' % (ownerclass, self.name)
  182. )
  183. if self.fget is not None:
  184. # use previous enum.property
  185. return self.fget(instance)
  186. elif self._attr_type == 'attr':
  187. # look up previous attibute
  188. return getattr(self._cls_type, self.name)
  189. elif self._attr_type == 'desc':
  190. # use previous descriptor
  191. return getattr(instance._value_, self.name)
  192. # look for a member by this name.
  193. try:
  194. return ownerclass._member_map_[self.name]
  195. except KeyError:
  196. raise AttributeError(
  197. '%r has no attribute %r' % (ownerclass, self.name)
  198. ) from None
  199. def __set__(self, instance, value):
  200. if self.fset is not None:
  201. return self.fset(instance, value)
  202. raise AttributeError(
  203. "<enum %r> cannot set attribute %r" % (self.clsname, self.name)
  204. )
  205. def __delete__(self, instance):
  206. if self.fdel is not None:
  207. return self.fdel(instance)
  208. raise AttributeError(
  209. "<enum %r> cannot delete attribute %r" % (self.clsname, self.name)
  210. )
  211. def __set_name__(self, ownerclass, name):
  212. self.name = name
  213. self.clsname = ownerclass.__name__
  214. class _proto_member:
  215. """
  216. intermediate step for enum members between class execution and final creation
  217. """
  218. def __init__(self, value):
  219. self.value = value
  220. def __set_name__(self, enum_class, member_name):
  221. """
  222. convert each quasi-member into an instance of the new enum class
  223. """
  224. # first step: remove ourself from enum_class
  225. delattr(enum_class, member_name)
  226. # second step: create member based on enum_class
  227. value = self.value
  228. if not isinstance(value, tuple):
  229. args = (value, )
  230. else:
  231. args = value
  232. if enum_class._member_type_ is tuple: # special case for tuple enums
  233. args = (args, ) # wrap it one more time
  234. if not enum_class._use_args_:
  235. enum_member = enum_class._new_member_(enum_class)
  236. else:
  237. enum_member = enum_class._new_member_(enum_class, *args)
  238. if not hasattr(enum_member, '_value_'):
  239. if enum_class._member_type_ is object:
  240. enum_member._value_ = value
  241. else:
  242. try:
  243. enum_member._value_ = enum_class._member_type_(*args)
  244. except Exception as exc:
  245. new_exc = TypeError(
  246. '_value_ not set in __new__, unable to create it'
  247. )
  248. new_exc.__cause__ = exc
  249. raise new_exc
  250. value = enum_member._value_
  251. enum_member._name_ = member_name
  252. enum_member.__objclass__ = enum_class
  253. enum_member.__init__(*args)
  254. enum_member._sort_order_ = len(enum_class._member_names_)
  255. if Flag is not None and issubclass(enum_class, Flag):
  256. if isinstance(value, int):
  257. enum_class._flag_mask_ |= value
  258. if _is_single_bit(value):
  259. enum_class._singles_mask_ |= value
  260. enum_class._all_bits_ = 2 ** ((enum_class._flag_mask_).bit_length()) - 1
  261. # If another member with the same value was already defined, the
  262. # new member becomes an alias to the existing one.
  263. try:
  264. try:
  265. # try to do a fast lookup to avoid the quadratic loop
  266. enum_member = enum_class._value2member_map_[value]
  267. except TypeError:
  268. for name, canonical_member in enum_class._member_map_.items():
  269. if canonical_member._value_ == value:
  270. enum_member = canonical_member
  271. break
  272. else:
  273. raise KeyError
  274. except KeyError:
  275. # this could still be an alias if the value is multi-bit and the
  276. # class is a flag class
  277. if (
  278. Flag is None
  279. or not issubclass(enum_class, Flag)
  280. ):
  281. # no other instances found, record this member in _member_names_
  282. enum_class._member_names_.append(member_name)
  283. elif (
  284. Flag is not None
  285. and issubclass(enum_class, Flag)
  286. and isinstance(value, int)
  287. and _is_single_bit(value)
  288. ):
  289. # no other instances found, record this member in _member_names_
  290. enum_class._member_names_.append(member_name)
  291. # if necessary, get redirect in place and then add it to _member_map_
  292. found_descriptor = None
  293. descriptor_type = None
  294. class_type = None
  295. for base in enum_class.__mro__[1:]:
  296. attr = base.__dict__.get(member_name)
  297. if attr is not None:
  298. if isinstance(attr, (property, DynamicClassAttribute)):
  299. found_descriptor = attr
  300. class_type = base
  301. descriptor_type = 'enum'
  302. break
  303. elif _is_descriptor(attr):
  304. found_descriptor = attr
  305. descriptor_type = descriptor_type or 'desc'
  306. class_type = class_type or base
  307. continue
  308. else:
  309. descriptor_type = 'attr'
  310. class_type = base
  311. if found_descriptor:
  312. redirect = property()
  313. redirect.member = enum_member
  314. redirect.__set_name__(enum_class, member_name)
  315. if descriptor_type in ('enum','desc'):
  316. # earlier descriptor found; copy fget, fset, fdel to this one.
  317. redirect.fget = getattr(found_descriptor, 'fget', None)
  318. redirect._get = getattr(found_descriptor, '__get__', None)
  319. redirect.fset = getattr(found_descriptor, 'fset', None)
  320. redirect._set = getattr(found_descriptor, '__set__', None)
  321. redirect.fdel = getattr(found_descriptor, 'fdel', None)
  322. redirect._del = getattr(found_descriptor, '__delete__', None)
  323. redirect._attr_type = descriptor_type
  324. redirect._cls_type = class_type
  325. setattr(enum_class, member_name, redirect)
  326. else:
  327. setattr(enum_class, member_name, enum_member)
  328. # now add to _member_map_ (even aliases)
  329. enum_class._member_map_[member_name] = enum_member
  330. try:
  331. # This may fail if value is not hashable. We can't add the value
  332. # to the map, and by-value lookups for this value will be
  333. # linear.
  334. enum_class._value2member_map_.setdefault(value, enum_member)
  335. except TypeError:
  336. # keep track of the value in a list so containment checks are quick
  337. enum_class._unhashable_values_.append(value)
  338. class _EnumDict(dict):
  339. """
  340. Track enum member order and ensure member names are not reused.
  341. EnumType will use the names found in self._member_names as the
  342. enumeration member names.
  343. """
  344. def __init__(self):
  345. super().__init__()
  346. self._member_names = {} # use a dict to keep insertion order
  347. self._last_values = []
  348. self._ignore = []
  349. self._auto_called = False
  350. def __setitem__(self, key, value):
  351. """
  352. Changes anything not dundered or not a descriptor.
  353. If an enum member name is used twice, an error is raised; duplicate
  354. values are not checked for.
  355. Single underscore (sunder) names are reserved.
  356. """
  357. if _is_internal_class(self._cls_name, value):
  358. import warnings
  359. warnings.warn(
  360. "In 3.13 classes created inside an enum will not become a member. "
  361. "Use the `member` decorator to keep the current behavior.",
  362. DeprecationWarning,
  363. stacklevel=2,
  364. )
  365. if _is_private(self._cls_name, key):
  366. # also do nothing, name will be a normal attribute
  367. pass
  368. elif _is_sunder(key):
  369. if key not in (
  370. '_order_',
  371. '_generate_next_value_', '_numeric_repr_', '_missing_', '_ignore_',
  372. '_iter_member_', '_iter_member_by_value_', '_iter_member_by_def_',
  373. ):
  374. raise ValueError(
  375. '_sunder_ names, such as %r, are reserved for future Enum use'
  376. % (key, )
  377. )
  378. if key == '_generate_next_value_':
  379. # check if members already defined as auto()
  380. if self._auto_called:
  381. raise TypeError("_generate_next_value_ must be defined before members")
  382. _gnv = value.__func__ if isinstance(value, staticmethod) else value
  383. setattr(self, '_generate_next_value', _gnv)
  384. elif key == '_ignore_':
  385. if isinstance(value, str):
  386. value = value.replace(',',' ').split()
  387. else:
  388. value = list(value)
  389. self._ignore = value
  390. already = set(value) & set(self._member_names)
  391. if already:
  392. raise ValueError(
  393. '_ignore_ cannot specify already set names: %r'
  394. % (already, )
  395. )
  396. elif _is_dunder(key):
  397. if key == '__order__':
  398. key = '_order_'
  399. elif key in self._member_names:
  400. # descriptor overwriting an enum?
  401. raise TypeError('%r already defined as %r' % (key, self[key]))
  402. elif key in self._ignore:
  403. pass
  404. elif isinstance(value, nonmember):
  405. # unwrap value here; it won't be processed by the below `else`
  406. value = value.value
  407. elif _is_descriptor(value):
  408. pass
  409. # TODO: uncomment next three lines in 3.13
  410. # elif _is_internal_class(self._cls_name, value):
  411. # # do nothing, name will be a normal attribute
  412. # pass
  413. else:
  414. if key in self:
  415. # enum overwriting a descriptor?
  416. raise TypeError('%r already defined as %r' % (key, self[key]))
  417. elif isinstance(value, member):
  418. # unwrap value here -- it will become a member
  419. value = value.value
  420. non_auto_store = True
  421. single = False
  422. if isinstance(value, auto):
  423. single = True
  424. value = (value, )
  425. if isinstance(value, tuple) and any(isinstance(v, auto) for v in value):
  426. # insist on an actual tuple, no subclasses, in keeping with only supporting
  427. # top-level auto() usage (not contained in any other data structure)
  428. auto_valued = []
  429. t = type(value)
  430. for v in value:
  431. if isinstance(v, auto):
  432. non_auto_store = False
  433. if v.value == _auto_null:
  434. v.value = self._generate_next_value(
  435. key, 1, len(self._member_names), self._last_values[:],
  436. )
  437. self._auto_called = True
  438. v = v.value
  439. self._last_values.append(v)
  440. auto_valued.append(v)
  441. if single:
  442. value = auto_valued[0]
  443. else:
  444. try:
  445. # accepts iterable as multiple arguments?
  446. value = t(auto_valued)
  447. except TypeError:
  448. # then pass them in singlely
  449. value = t(*auto_valued)
  450. self._member_names[key] = None
  451. if non_auto_store:
  452. self._last_values.append(value)
  453. super().__setitem__(key, value)
  454. def update(self, members, **more_members):
  455. try:
  456. for name in members.keys():
  457. self[name] = members[name]
  458. except AttributeError:
  459. for name, value in members:
  460. self[name] = value
  461. for name, value in more_members.items():
  462. self[name] = value
  463. class EnumType(type):
  464. """
  465. Metaclass for Enum
  466. """
  467. @classmethod
  468. def __prepare__(metacls, cls, bases, **kwds):
  469. # check that previous enum members do not exist
  470. metacls._check_for_existing_members_(cls, bases)
  471. # create the namespace dict
  472. enum_dict = _EnumDict()
  473. enum_dict._cls_name = cls
  474. # inherit previous flags and _generate_next_value_ function
  475. member_type, first_enum = metacls._get_mixins_(cls, bases)
  476. if first_enum is not None:
  477. enum_dict['_generate_next_value_'] = getattr(
  478. first_enum, '_generate_next_value_', None,
  479. )
  480. return enum_dict
  481. def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **kwds):
  482. # an Enum class is final once enumeration items have been defined; it
  483. # cannot be mixed with other types (int, float, etc.) if it has an
  484. # inherited __new__ unless a new __new__ is defined (or the resulting
  485. # class will fail).
  486. #
  487. if _simple:
  488. return super().__new__(metacls, cls, bases, classdict, **kwds)
  489. #
  490. # remove any keys listed in _ignore_
  491. classdict.setdefault('_ignore_', []).append('_ignore_')
  492. ignore = classdict['_ignore_']
  493. for key in ignore:
  494. classdict.pop(key, None)
  495. #
  496. # grab member names
  497. member_names = classdict._member_names
  498. #
  499. # check for illegal enum names (any others?)
  500. invalid_names = set(member_names) & {'mro', ''}
  501. if invalid_names:
  502. raise ValueError('invalid enum member name(s) %s' % (
  503. ','.join(repr(n) for n in invalid_names)
  504. ))
  505. #
  506. # adjust the sunders
  507. _order_ = classdict.pop('_order_', None)
  508. _gnv = classdict.get('_generate_next_value_')
  509. if _gnv is not None and type(_gnv) is not staticmethod:
  510. _gnv = staticmethod(_gnv)
  511. # convert to normal dict
  512. classdict = dict(classdict.items())
  513. if _gnv is not None:
  514. classdict['_generate_next_value_'] = _gnv
  515. #
  516. # data type of member and the controlling Enum class
  517. member_type, first_enum = metacls._get_mixins_(cls, bases)
  518. __new__, save_new, use_args = metacls._find_new_(
  519. classdict, member_type, first_enum,
  520. )
  521. classdict['_new_member_'] = __new__
  522. classdict['_use_args_'] = use_args
  523. #
  524. # convert future enum members into temporary _proto_members
  525. for name in member_names:
  526. value = classdict[name]
  527. classdict[name] = _proto_member(value)
  528. #
  529. # house-keeping structures
  530. classdict['_member_names_'] = []
  531. classdict['_member_map_'] = {}
  532. classdict['_value2member_map_'] = {}
  533. classdict['_unhashable_values_'] = []
  534. classdict['_member_type_'] = member_type
  535. # now set the __repr__ for the value
  536. classdict['_value_repr_'] = metacls._find_data_repr_(cls, bases)
  537. #
  538. # Flag structures (will be removed if final class is not a Flag
  539. classdict['_boundary_'] = (
  540. boundary
  541. or getattr(first_enum, '_boundary_', None)
  542. )
  543. classdict['_flag_mask_'] = 0
  544. classdict['_singles_mask_'] = 0
  545. classdict['_all_bits_'] = 0
  546. classdict['_inverted_'] = None
  547. try:
  548. exc = None
  549. enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
  550. except Exception as e:
  551. # since 3.12 the line "Error calling __set_name__ on '_proto_member' instance ..."
  552. # is tacked on to the error instead of raising a RuntimeError
  553. # recreate the exception to discard
  554. exc = type(e)(str(e))
  555. exc.__cause__ = e.__cause__
  556. exc.__context__ = e.__context__
  557. tb = e.__traceback__
  558. if exc is not None:
  559. raise exc.with_traceback(tb)
  560. #
  561. # update classdict with any changes made by __init_subclass__
  562. classdict.update(enum_class.__dict__)
  563. #
  564. # double check that repr and friends are not the mixin's or various
  565. # things break (such as pickle)
  566. # however, if the method is defined in the Enum itself, don't replace
  567. # it
  568. #
  569. # Also, special handling for ReprEnum
  570. if ReprEnum is not None and ReprEnum in bases:
  571. if member_type is object:
  572. raise TypeError(
  573. 'ReprEnum subclasses must be mixed with a data type (i.e.'
  574. ' int, str, float, etc.)'
  575. )
  576. if '__format__' not in classdict:
  577. enum_class.__format__ = member_type.__format__
  578. classdict['__format__'] = enum_class.__format__
  579. if '__str__' not in classdict:
  580. method = member_type.__str__
  581. if method is object.__str__:
  582. # if member_type does not define __str__, object.__str__ will use
  583. # its __repr__ instead, so we'll also use its __repr__
  584. method = member_type.__repr__
  585. enum_class.__str__ = method
  586. classdict['__str__'] = enum_class.__str__
  587. for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
  588. if name not in classdict:
  589. # check for mixin overrides before replacing
  590. enum_method = getattr(first_enum, name)
  591. found_method = getattr(enum_class, name)
  592. object_method = getattr(object, name)
  593. data_type_method = getattr(member_type, name)
  594. if found_method in (data_type_method, object_method):
  595. setattr(enum_class, name, enum_method)
  596. #
  597. # for Flag, add __or__, __and__, __xor__, and __invert__
  598. if Flag is not None and issubclass(enum_class, Flag):
  599. for name in (
  600. '__or__', '__and__', '__xor__',
  601. '__ror__', '__rand__', '__rxor__',
  602. '__invert__'
  603. ):
  604. if name not in classdict:
  605. enum_method = getattr(Flag, name)
  606. setattr(enum_class, name, enum_method)
  607. classdict[name] = enum_method
  608. #
  609. # replace any other __new__ with our own (as long as Enum is not None,
  610. # anyway) -- again, this is to support pickle
  611. if Enum is not None:
  612. # if the user defined their own __new__, save it before it gets
  613. # clobbered in case they subclass later
  614. if save_new:
  615. enum_class.__new_member__ = __new__
  616. enum_class.__new__ = Enum.__new__
  617. #
  618. # py3 support for definition order (helps keep py2/py3 code in sync)
  619. #
  620. # _order_ checking is spread out into three/four steps
  621. # - if enum_class is a Flag:
  622. # - remove any non-single-bit flags from _order_
  623. # - remove any aliases from _order_
  624. # - check that _order_ and _member_names_ match
  625. #
  626. # step 1: ensure we have a list
  627. if _order_ is not None:
  628. if isinstance(_order_, str):
  629. _order_ = _order_.replace(',', ' ').split()
  630. #
  631. # remove Flag structures if final class is not a Flag
  632. if (
  633. Flag is None and cls != 'Flag'
  634. or Flag is not None and not issubclass(enum_class, Flag)
  635. ):
  636. delattr(enum_class, '_boundary_')
  637. delattr(enum_class, '_flag_mask_')
  638. delattr(enum_class, '_singles_mask_')
  639. delattr(enum_class, '_all_bits_')
  640. delattr(enum_class, '_inverted_')
  641. elif Flag is not None and issubclass(enum_class, Flag):
  642. # set correct __iter__
  643. member_list = [m._value_ for m in enum_class]
  644. if member_list != sorted(member_list):
  645. enum_class._iter_member_ = enum_class._iter_member_by_def_
  646. if _order_:
  647. # _order_ step 2: remove any items from _order_ that are not single-bit
  648. _order_ = [
  649. o
  650. for o in _order_
  651. if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_)
  652. ]
  653. #
  654. if _order_:
  655. # _order_ step 3: remove aliases from _order_
  656. _order_ = [
  657. o
  658. for o in _order_
  659. if (
  660. o not in enum_class._member_map_
  661. or
  662. (o in enum_class._member_map_ and o in enum_class._member_names_)
  663. )]
  664. # _order_ step 4: verify that _order_ and _member_names_ match
  665. if _order_ != enum_class._member_names_:
  666. raise TypeError(
  667. 'member order does not match _order_:\n %r\n %r'
  668. % (enum_class._member_names_, _order_)
  669. )
  670. #
  671. return enum_class
  672. def __bool__(cls):
  673. """
  674. classes/types should always be True.
  675. """
  676. return True
  677. def __call__(cls, value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None):
  678. """
  679. Either returns an existing member, or creates a new enum class.
  680. This method is used both when an enum class is given a value to match
  681. to an enumeration member (i.e. Color(3)) and for the functional API
  682. (i.e. Color = Enum('Color', names='RED GREEN BLUE')).
  683. The value lookup branch is chosen if the enum is final.
  684. When used for the functional API:
  685. `value` will be the name of the new class.
  686. `names` should be either a string of white-space/comma delimited names
  687. (values will start at `start`), or an iterator/mapping of name, value pairs.
  688. `module` should be set to the module this class is being created in;
  689. if it is not set, an attempt to find that module will be made, but if
  690. it fails the class will not be picklable.
  691. `qualname` should be set to the actual location this class can be found
  692. at in its module; by default it is set to the global scope. If this is
  693. not correct, unpickling will fail in some circumstances.
  694. `type`, if set, will be mixed in as the first base class.
  695. """
  696. if cls._member_map_:
  697. # simple value lookup if members exist
  698. if names is not _not_given:
  699. value = (value, names) + values
  700. return cls.__new__(cls, value)
  701. # otherwise, functional API: we're creating a new Enum type
  702. if names is _not_given and type is None:
  703. # no body? no data-type? possibly wrong usage
  704. raise TypeError(
  705. f"{cls} has no members; specify `names=()` if you meant to create a new, empty, enum"
  706. )
  707. return cls._create_(
  708. class_name=value,
  709. names=None if names is _not_given else names,
  710. module=module,
  711. qualname=qualname,
  712. type=type,
  713. start=start,
  714. boundary=boundary,
  715. )
  716. def __contains__(cls, value):
  717. """Return True if `value` is in `cls`.
  718. `value` is in `cls` if:
  719. 1) `value` is a member of `cls`, or
  720. 2) `value` is the value of one of the `cls`'s members.
  721. """
  722. if isinstance(value, cls):
  723. return True
  724. return value in cls._value2member_map_ or value in cls._unhashable_values_
  725. def __delattr__(cls, attr):
  726. # nicer error message when someone tries to delete an attribute
  727. # (see issue19025).
  728. if attr in cls._member_map_:
  729. raise AttributeError("%r cannot delete member %r." % (cls.__name__, attr))
  730. super().__delattr__(attr)
  731. def __dir__(cls):
  732. interesting = set([
  733. '__class__', '__contains__', '__doc__', '__getitem__',
  734. '__iter__', '__len__', '__members__', '__module__',
  735. '__name__', '__qualname__',
  736. ]
  737. + cls._member_names_
  738. )
  739. if cls._new_member_ is not object.__new__:
  740. interesting.add('__new__')
  741. if cls.__init_subclass__ is not object.__init_subclass__:
  742. interesting.add('__init_subclass__')
  743. if cls._member_type_ is object:
  744. return sorted(interesting)
  745. else:
  746. # return whatever mixed-in data type has
  747. return sorted(set(dir(cls._member_type_)) | interesting)
  748. def __getitem__(cls, name):
  749. """
  750. Return the member matching `name`.
  751. """
  752. return cls._member_map_[name]
  753. def __iter__(cls):
  754. """
  755. Return members in definition order.
  756. """
  757. return (cls._member_map_[name] for name in cls._member_names_)
  758. def __len__(cls):
  759. """
  760. Return the number of members (no aliases)
  761. """
  762. return len(cls._member_names_)
  763. @bltns.property
  764. def __members__(cls):
  765. """
  766. Returns a mapping of member name->value.
  767. This mapping lists all enum members, including aliases. Note that this
  768. is a read-only view of the internal mapping.
  769. """
  770. return MappingProxyType(cls._member_map_)
  771. def __repr__(cls):
  772. if Flag is not None and issubclass(cls, Flag):
  773. return "<flag %r>" % cls.__name__
  774. else:
  775. return "<enum %r>" % cls.__name__
  776. def __reversed__(cls):
  777. """
  778. Return members in reverse definition order.
  779. """
  780. return (cls._member_map_[name] for name in reversed(cls._member_names_))
  781. def __setattr__(cls, name, value):
  782. """
  783. Block attempts to reassign Enum members.
  784. A simple assignment to the class namespace only changes one of the
  785. several possible ways to get an Enum member from the Enum class,
  786. resulting in an inconsistent Enumeration.
  787. """
  788. member_map = cls.__dict__.get('_member_map_', {})
  789. if name in member_map:
  790. raise AttributeError('cannot reassign member %r' % (name, ))
  791. super().__setattr__(name, value)
  792. def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1, boundary=None):
  793. """
  794. Convenience method to create a new Enum class.
  795. `names` can be:
  796. * A string containing member names, separated either with spaces or
  797. commas. Values are incremented by 1 from `start`.
  798. * An iterable of member names. Values are incremented by 1 from `start`.
  799. * An iterable of (member name, value) pairs.
  800. * A mapping of member name -> value pairs.
  801. """
  802. metacls = cls.__class__
  803. bases = (cls, ) if type is None else (type, cls)
  804. _, first_enum = cls._get_mixins_(class_name, bases)
  805. classdict = metacls.__prepare__(class_name, bases)
  806. # special processing needed for names?
  807. if isinstance(names, str):
  808. names = names.replace(',', ' ').split()
  809. if isinstance(names, (tuple, list)) and names and isinstance(names[0], str):
  810. original_names, names = names, []
  811. last_values = []
  812. for count, name in enumerate(original_names):
  813. value = first_enum._generate_next_value_(name, start, count, last_values[:])
  814. last_values.append(value)
  815. names.append((name, value))
  816. if names is None:
  817. names = ()
  818. # Here, names is either an iterable of (name, value) or a mapping.
  819. for item in names:
  820. if isinstance(item, str):
  821. member_name, member_value = item, names[item]
  822. else:
  823. member_name, member_value = item
  824. classdict[member_name] = member_value
  825. if module is None:
  826. try:
  827. module = sys._getframemodulename(2)
  828. except AttributeError:
  829. # Fall back on _getframe if _getframemodulename is missing
  830. try:
  831. module = sys._getframe(2).f_globals['__name__']
  832. except (AttributeError, ValueError, KeyError):
  833. pass
  834. if module is None:
  835. _make_class_unpicklable(classdict)
  836. else:
  837. classdict['__module__'] = module
  838. if qualname is not None:
  839. classdict['__qualname__'] = qualname
  840. return metacls.__new__(metacls, class_name, bases, classdict, boundary=boundary)
  841. def _convert_(cls, name, module, filter, source=None, *, boundary=None, as_global=False):
  842. """
  843. Create a new Enum subclass that replaces a collection of global constants
  844. """
  845. # convert all constants from source (or module) that pass filter() to
  846. # a new Enum called name, and export the enum and its members back to
  847. # module;
  848. # also, replace the __reduce_ex__ method so unpickling works in
  849. # previous Python versions
  850. module_globals = sys.modules[module].__dict__
  851. if source:
  852. source = source.__dict__
  853. else:
  854. source = module_globals
  855. # _value2member_map_ is populated in the same order every time
  856. # for a consistent reverse mapping of number to name when there
  857. # are multiple names for the same number.
  858. members = [
  859. (name, value)
  860. for name, value in source.items()
  861. if filter(name)]
  862. try:
  863. # sort by value
  864. members.sort(key=lambda t: (t[1], t[0]))
  865. except TypeError:
  866. # unless some values aren't comparable, in which case sort by name
  867. members.sort(key=lambda t: t[0])
  868. body = {t[0]: t[1] for t in members}
  869. body['__module__'] = module
  870. tmp_cls = type(name, (object, ), body)
  871. cls = _simple_enum(etype=cls, boundary=boundary or KEEP)(tmp_cls)
  872. if as_global:
  873. global_enum(cls)
  874. else:
  875. sys.modules[cls.__module__].__dict__.update(cls.__members__)
  876. module_globals[name] = cls
  877. return cls
  878. @classmethod
  879. def _check_for_existing_members_(mcls, class_name, bases):
  880. for chain in bases:
  881. for base in chain.__mro__:
  882. if isinstance(base, EnumType) and base._member_names_:
  883. raise TypeError(
  884. "<enum %r> cannot extend %r"
  885. % (class_name, base)
  886. )
  887. @classmethod
  888. def _get_mixins_(mcls, class_name, bases):
  889. """
  890. Returns the type for creating enum members, and the first inherited
  891. enum class.
  892. bases: the tuple of bases that was given to __new__
  893. """
  894. if not bases:
  895. return object, Enum
  896. # ensure final parent class is an Enum derivative, find any concrete
  897. # data type, and check that Enum has no members
  898. first_enum = bases[-1]
  899. if not isinstance(first_enum, EnumType):
  900. raise TypeError("new enumerations should be created as "
  901. "`EnumName([mixin_type, ...] [data_type,] enum_type)`")
  902. member_type = mcls._find_data_type_(class_name, bases) or object
  903. return member_type, first_enum
  904. @classmethod
  905. def _find_data_repr_(mcls, class_name, bases):
  906. for chain in bases:
  907. for base in chain.__mro__:
  908. if base is object:
  909. continue
  910. elif isinstance(base, EnumType):
  911. # if we hit an Enum, use it's _value_repr_
  912. return base._value_repr_
  913. elif '__repr__' in base.__dict__:
  914. # this is our data repr
  915. # double-check if a dataclass with a default __repr__
  916. if (
  917. '__dataclass_fields__' in base.__dict__
  918. and '__dataclass_params__' in base.__dict__
  919. and base.__dict__['__dataclass_params__'].repr
  920. ):
  921. return _dataclass_repr
  922. else:
  923. return base.__dict__['__repr__']
  924. return None
  925. @classmethod
  926. def _find_data_type_(mcls, class_name, bases):
  927. # a datatype has a __new__ method, or a __dataclass_fields__ attribute
  928. data_types = set()
  929. base_chain = set()
  930. for chain in bases:
  931. candidate = None
  932. for base in chain.__mro__:
  933. base_chain.add(base)
  934. if base is object:
  935. continue
  936. elif isinstance(base, EnumType):
  937. if base._member_type_ is not object:
  938. data_types.add(base._member_type_)
  939. break
  940. elif '__new__' in base.__dict__ or '__dataclass_fields__' in base.__dict__:
  941. data_types.add(candidate or base)
  942. break
  943. else:
  944. candidate = candidate or base
  945. if len(data_types) > 1:
  946. raise TypeError('too many data types for %r: %r' % (class_name, data_types))
  947. elif data_types:
  948. return data_types.pop()
  949. else:
  950. return None
  951. @classmethod
  952. def _find_new_(mcls, classdict, member_type, first_enum):
  953. """
  954. Returns the __new__ to be used for creating the enum members.
  955. classdict: the class dictionary given to __new__
  956. member_type: the data type whose __new__ will be used by default
  957. first_enum: enumeration to check for an overriding __new__
  958. """
  959. # now find the correct __new__, checking to see of one was defined
  960. # by the user; also check earlier enum classes in case a __new__ was
  961. # saved as __new_member__
  962. __new__ = classdict.get('__new__', None)
  963. # should __new__ be saved as __new_member__ later?
  964. save_new = first_enum is not None and __new__ is not None
  965. if __new__ is None:
  966. # check all possibles for __new_member__ before falling back to
  967. # __new__
  968. for method in ('__new_member__', '__new__'):
  969. for possible in (member_type, first_enum):
  970. target = getattr(possible, method, None)
  971. if target not in {
  972. None,
  973. None.__new__,
  974. object.__new__,
  975. Enum.__new__,
  976. }:
  977. __new__ = target
  978. break
  979. if __new__ is not None:
  980. break
  981. else:
  982. __new__ = object.__new__
  983. # if a non-object.__new__ is used then whatever value/tuple was
  984. # assigned to the enum member name will be passed to __new__ and to the
  985. # new enum member's __init__
  986. if first_enum is None or __new__ in (Enum.__new__, object.__new__):
  987. use_args = False
  988. else:
  989. use_args = True
  990. return __new__, save_new, use_args
  991. EnumMeta = EnumType
  992. class Enum(metaclass=EnumType):
  993. """
  994. Create a collection of name/value pairs.
  995. Example enumeration:
  996. >>> class Color(Enum):
  997. ... RED = 1
  998. ... BLUE = 2
  999. ... GREEN = 3
  1000. Access them by:
  1001. - attribute access:
  1002. >>> Color.RED
  1003. <Color.RED: 1>
  1004. - value lookup:
  1005. >>> Color(1)
  1006. <Color.RED: 1>
  1007. - name lookup:
  1008. >>> Color['RED']
  1009. <Color.RED: 1>
  1010. Enumerations can be iterated over, and know how many members they have:
  1011. >>> len(Color)
  1012. 3
  1013. >>> list(Color)
  1014. [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
  1015. Methods can be added to enumerations, and members can have their own
  1016. attributes -- see the documentation for details.
  1017. """
  1018. @classmethod
  1019. def __signature__(cls):
  1020. if cls._member_names_:
  1021. return '(*values)'
  1022. else:
  1023. return '(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)'
  1024. def __new__(cls, value):
  1025. # all enum instances are actually created during class construction
  1026. # without calling this method; this method is called by the metaclass'
  1027. # __call__ (i.e. Color(3) ), and by pickle
  1028. if type(value) is cls:
  1029. # For lookups like Color(Color.RED)
  1030. return value
  1031. # by-value search for a matching enum member
  1032. # see if it's in the reverse mapping (for hashable values)
  1033. try:
  1034. return cls._value2member_map_[value]
  1035. except KeyError:
  1036. # Not found, no need to do long O(n) search
  1037. pass
  1038. except TypeError:
  1039. # not there, now do long search -- O(n) behavior
  1040. for member in cls._member_map_.values():
  1041. if member._value_ == value:
  1042. return member
  1043. # still not found -- verify that members exist, in-case somebody got here mistakenly
  1044. # (such as via super when trying to override __new__)
  1045. if not cls._member_map_:
  1046. raise TypeError("%r has no members defined" % cls)
  1047. #
  1048. # still not found -- try _missing_ hook
  1049. try:
  1050. exc = None
  1051. result = cls._missing_(value)
  1052. except Exception as e:
  1053. exc = e
  1054. result = None
  1055. try:
  1056. if isinstance(result, cls):
  1057. return result
  1058. elif (
  1059. Flag is not None and issubclass(cls, Flag)
  1060. and cls._boundary_ is EJECT and isinstance(result, int)
  1061. ):
  1062. return result
  1063. else:
  1064. ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__))
  1065. if result is None and exc is None:
  1066. raise ve_exc
  1067. elif exc is None:
  1068. exc = TypeError(
  1069. 'error in %s._missing_: returned %r instead of None or a valid member'
  1070. % (cls.__name__, result)
  1071. )
  1072. if not isinstance(exc, ValueError):
  1073. exc.__context__ = ve_exc
  1074. raise exc
  1075. finally:
  1076. # ensure all variables that could hold an exception are destroyed
  1077. exc = None
  1078. ve_exc = None
  1079. def __init__(self, *args, **kwds):
  1080. pass
  1081. @staticmethod
  1082. def _generate_next_value_(name, start, count, last_values):
  1083. """
  1084. Generate the next value when not given.
  1085. name: the name of the member
  1086. start: the initial start value or None
  1087. count: the number of existing members
  1088. last_values: the list of values assigned
  1089. """
  1090. if not last_values:
  1091. return start
  1092. try:
  1093. last = last_values[-1]
  1094. last_values.sort()
  1095. if last == last_values[-1]:
  1096. # no difference between old and new methods
  1097. return last + 1
  1098. else:
  1099. # trigger old method (with warning)
  1100. raise TypeError
  1101. except TypeError:
  1102. import warnings
  1103. warnings.warn(
  1104. "In 3.13 the default `auto()`/`_generate_next_value_` will require all values to be sortable and support adding +1\n"
  1105. "and the value returned will be the largest value in the enum incremented by 1",
  1106. DeprecationWarning,
  1107. stacklevel=3,
  1108. )
  1109. for v in reversed(last_values):
  1110. try:
  1111. return v + 1
  1112. except TypeError:
  1113. pass
  1114. return start
  1115. @classmethod
  1116. def _missing_(cls, value):
  1117. return None
  1118. def __repr__(self):
  1119. v_repr = self.__class__._value_repr_ or repr
  1120. return "<%s.%s: %s>" % (self.__class__.__name__, self._name_, v_repr(self._value_))
  1121. def __str__(self):
  1122. return "%s.%s" % (self.__class__.__name__, self._name_, )
  1123. def __dir__(self):
  1124. """
  1125. Returns public methods and other interesting attributes.
  1126. """
  1127. interesting = set()
  1128. if self.__class__._member_type_ is not object:
  1129. interesting = set(object.__dir__(self))
  1130. for name in getattr(self, '__dict__', []):
  1131. if name[0] != '_' and name not in self._member_map_:
  1132. interesting.add(name)
  1133. for cls in self.__class__.mro():
  1134. for name, obj in cls.__dict__.items():
  1135. if name[0] == '_':
  1136. continue
  1137. if isinstance(obj, property):
  1138. # that's an enum.property
  1139. if obj.fget is not None or name not in self._member_map_:
  1140. interesting.add(name)
  1141. else:
  1142. # in case it was added by `dir(self)`
  1143. interesting.discard(name)
  1144. elif name not in self._member_map_:
  1145. interesting.add(name)
  1146. names = sorted(
  1147. set(['__class__', '__doc__', '__eq__', '__hash__', '__module__'])
  1148. | interesting
  1149. )
  1150. return names
  1151. def __format__(self, format_spec):
  1152. return str.__format__(str(self), format_spec)
  1153. def __hash__(self):
  1154. return hash(self._name_)
  1155. def __reduce_ex__(self, proto):
  1156. return self.__class__, (self._value_, )
  1157. def __deepcopy__(self,memo):
  1158. return self
  1159. def __copy__(self):
  1160. return self
  1161. # enum.property is used to provide access to the `name` and
  1162. # `value` attributes of enum members while keeping some measure of
  1163. # protection from modification, while still allowing for an enumeration
  1164. # to have members named `name` and `value`. This works because each
  1165. # instance of enum.property saves its companion member, which it returns
  1166. # on class lookup; on instance lookup it either executes a provided function
  1167. # or raises an AttributeError.
  1168. @property
  1169. def name(self):
  1170. """The name of the Enum member."""
  1171. return self._name_
  1172. @property
  1173. def value(self):
  1174. """The value of the Enum member."""
  1175. return self._value_
  1176. class ReprEnum(Enum):
  1177. """
  1178. Only changes the repr(), leaving str() and format() to the mixed-in type.
  1179. """
  1180. class IntEnum(int, ReprEnum):
  1181. """
  1182. Enum where members are also (and must be) ints
  1183. """
  1184. class StrEnum(str, ReprEnum):
  1185. """
  1186. Enum where members are also (and must be) strings
  1187. """
  1188. def __new__(cls, *values):
  1189. "values must already be of type `str`"
  1190. if len(values) > 3:
  1191. raise TypeError('too many arguments for str(): %r' % (values, ))
  1192. if len(values) == 1:
  1193. # it must be a string
  1194. if not isinstance(values[0], str):
  1195. raise TypeError('%r is not a string' % (values[0], ))
  1196. if len(values) >= 2:
  1197. # check that encoding argument is a string
  1198. if not isinstance(values[1], str):
  1199. raise TypeError('encoding must be a string, not %r' % (values[1], ))
  1200. if len(values) == 3:
  1201. # check that errors argument is a string
  1202. if not isinstance(values[2], str):
  1203. raise TypeError('errors must be a string, not %r' % (values[2]))
  1204. value = str(*values)
  1205. member = str.__new__(cls, value)
  1206. member._value_ = value
  1207. return member
  1208. @staticmethod
  1209. def _generate_next_value_(name, start, count, last_values):
  1210. """
  1211. Return the lower-cased version of the member name.
  1212. """
  1213. return name.lower()
  1214. def pickle_by_global_name(self, proto):
  1215. # should not be used with Flag-type enums
  1216. return self.name
  1217. _reduce_ex_by_global_name = pickle_by_global_name
  1218. def pickle_by_enum_name(self, proto):
  1219. # should not be used with Flag-type enums
  1220. return getattr, (self.__class__, self._name_)
  1221. class FlagBoundary(StrEnum):
  1222. """
  1223. control how out of range values are handled
  1224. "strict" -> error is raised [default for Flag]
  1225. "conform" -> extra bits are discarded
  1226. "eject" -> lose flag status
  1227. "keep" -> keep flag status and all bits [default for IntFlag]
  1228. """
  1229. STRICT = auto()
  1230. CONFORM = auto()
  1231. EJECT = auto()
  1232. KEEP = auto()
  1233. STRICT, CONFORM, EJECT, KEEP = FlagBoundary
  1234. class Flag(Enum, boundary=STRICT):
  1235. """
  1236. Support for flags
  1237. """
  1238. _numeric_repr_ = repr
  1239. @staticmethod
  1240. def _generate_next_value_(name, start, count, last_values):
  1241. """
  1242. Generate the next value when not given.
  1243. name: the name of the member
  1244. start: the initial start value or None
  1245. count: the number of existing members
  1246. last_values: the last value assigned or None
  1247. """
  1248. if not count:
  1249. return start if start is not None else 1
  1250. last_value = max(last_values)
  1251. try:
  1252. high_bit = _high_bit(last_value)
  1253. except Exception:
  1254. raise TypeError('invalid flag value %r' % last_value) from None
  1255. return 2 ** (high_bit+1)
  1256. @classmethod
  1257. def _iter_member_by_value_(cls, value):
  1258. """
  1259. Extract all members from the value in definition (i.e. increasing value) order.
  1260. """
  1261. for val in _iter_bits_lsb(value & cls._flag_mask_):
  1262. yield cls._value2member_map_.get(val)
  1263. _iter_member_ = _iter_member_by_value_
  1264. @classmethod
  1265. def _iter_member_by_def_(cls, value):
  1266. """
  1267. Extract all members from the value in definition order.
  1268. """
  1269. yield from sorted(
  1270. cls._iter_member_by_value_(value),
  1271. key=lambda m: m._sort_order_,
  1272. )
  1273. @classmethod
  1274. def _missing_(cls, value):
  1275. """
  1276. Create a composite member containing all canonical members present in `value`.
  1277. If non-member values are present, result depends on `_boundary_` setting.
  1278. """
  1279. if not isinstance(value, int):
  1280. raise ValueError(
  1281. "%r is not a valid %s" % (value, cls.__qualname__)
  1282. )
  1283. # check boundaries
  1284. # - value must be in range (e.g. -16 <-> +15, i.e. ~15 <-> 15)
  1285. # - value must not include any skipped flags (e.g. if bit 2 is not
  1286. # defined, then 0d10 is invalid)
  1287. flag_mask = cls._flag_mask_
  1288. singles_mask = cls._singles_mask_
  1289. all_bits = cls._all_bits_
  1290. neg_value = None
  1291. if (
  1292. not ~all_bits <= value <= all_bits
  1293. or value & (all_bits ^ flag_mask)
  1294. ):
  1295. if cls._boundary_ is STRICT:
  1296. max_bits = max(value.bit_length(), flag_mask.bit_length())
  1297. raise ValueError(
  1298. "%r invalid value %r\n given %s\n allowed %s" % (
  1299. cls, value, bin(value, max_bits), bin(flag_mask, max_bits),
  1300. ))
  1301. elif cls._boundary_ is CONFORM:
  1302. value = value & flag_mask
  1303. elif cls._boundary_ is EJECT:
  1304. return value
  1305. elif cls._boundary_ is KEEP:
  1306. if value < 0:
  1307. value = (
  1308. max(all_bits+1, 2**(value.bit_length()))
  1309. + value
  1310. )
  1311. else:
  1312. raise ValueError(
  1313. '%r unknown flag boundary %r' % (cls, cls._boundary_, )
  1314. )
  1315. if value < 0:
  1316. neg_value = value
  1317. value = all_bits + 1 + value
  1318. # get members and unknown
  1319. unknown = value & ~flag_mask
  1320. aliases = value & ~singles_mask
  1321. member_value = value & singles_mask
  1322. if unknown and cls._boundary_ is not KEEP:
  1323. raise ValueError(
  1324. '%s(%r) --> unknown values %r [%s]'
  1325. % (cls.__name__, value, unknown, bin(unknown))
  1326. )
  1327. # normal Flag?
  1328. if cls._member_type_ is object:
  1329. # construct a singleton enum pseudo-member
  1330. pseudo_member = object.__new__(cls)
  1331. else:
  1332. pseudo_member = cls._member_type_.__new__(cls, value)
  1333. if not hasattr(pseudo_member, '_value_'):
  1334. pseudo_member._value_ = value
  1335. if member_value or aliases:
  1336. members = []
  1337. combined_value = 0
  1338. for m in cls._iter_member_(member_value):
  1339. members.append(m)
  1340. combined_value |= m._value_
  1341. if aliases:
  1342. value = member_value | aliases
  1343. for n, pm in cls._member_map_.items():
  1344. if pm not in members and pm._value_ and pm._value_ & value == pm._value_:
  1345. members.append(pm)
  1346. combined_value |= pm._value_
  1347. unknown = value ^ combined_value
  1348. pseudo_member._name_ = '|'.join([m._name_ for m in members])
  1349. if not combined_value:
  1350. pseudo_member._name_ = None
  1351. elif unknown and cls._boundary_ is STRICT:
  1352. raise ValueError('%r: no members with value %r' % (cls, unknown))
  1353. elif unknown:
  1354. pseudo_member._name_ += '|%s' % cls._numeric_repr_(unknown)
  1355. else:
  1356. pseudo_member._name_ = None
  1357. # use setdefault in case another thread already created a composite
  1358. # with this value
  1359. # note: zero is a special case -- always add it
  1360. pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member)
  1361. if neg_value is not None:
  1362. cls._value2member_map_[neg_value] = pseudo_member
  1363. return pseudo_member
  1364. def __contains__(self, other):
  1365. """
  1366. Returns True if self has at least the same flags set as other.
  1367. """
  1368. if not isinstance(other, self.__class__):
  1369. raise TypeError(
  1370. "unsupported operand type(s) for 'in': %r and %r" % (
  1371. type(other).__qualname__, self.__class__.__qualname__))
  1372. return other._value_ & self._value_ == other._value_
  1373. def __iter__(self):
  1374. """
  1375. Returns flags in definition order.
  1376. """
  1377. yield from self._iter_member_(self._value_)
  1378. def __len__(self):
  1379. return self._value_.bit_count()
  1380. def __repr__(self):
  1381. cls_name = self.__class__.__name__
  1382. v_repr = self.__class__._value_repr_ or repr
  1383. if self._name_ is None:
  1384. return "<%s: %s>" % (cls_name, v_repr(self._value_))
  1385. else:
  1386. return "<%s.%s: %s>" % (cls_name, self._name_, v_repr(self._value_))
  1387. def __str__(self):
  1388. cls_name = self.__class__.__name__
  1389. if self._name_ is None:
  1390. return '%s(%r)' % (cls_name, self._value_)
  1391. else:
  1392. return "%s.%s" % (cls_name, self._name_)
  1393. def __bool__(self):
  1394. return bool(self._value_)
  1395. def _get_value(self, flag):
  1396. if isinstance(flag, self.__class__):
  1397. return flag._value_
  1398. elif self._member_type_ is not object and isinstance(flag, self._member_type_):
  1399. return flag
  1400. return NotImplemented
  1401. def __or__(self, other):
  1402. other_value = self._get_value(other)
  1403. if other_value is NotImplemented:
  1404. return NotImplemented
  1405. for flag in self, other:
  1406. if self._get_value(flag) is None:
  1407. raise TypeError(f"'{flag}' cannot be combined with other flags with |")
  1408. value = self._value_
  1409. return self.__class__(value | other_value)
  1410. def __and__(self, other):
  1411. other_value = self._get_value(other)
  1412. if other_value is NotImplemented:
  1413. return NotImplemented
  1414. for flag in self, other:
  1415. if self._get_value(flag) is None:
  1416. raise TypeError(f"'{flag}' cannot be combined with other flags with &")
  1417. value = self._value_
  1418. return self.__class__(value & other_value)
  1419. def __xor__(self, other):
  1420. other_value = self._get_value(other)
  1421. if other_value is NotImplemented:
  1422. return NotImplemented
  1423. for flag in self, other:
  1424. if self._get_value(flag) is None:
  1425. raise TypeError(f"'{flag}' cannot be combined with other flags with ^")
  1426. value = self._value_
  1427. return self.__class__(value ^ other_value)
  1428. def __invert__(self):
  1429. if self._get_value(self) is None:
  1430. raise TypeError(f"'{self}' cannot be inverted")
  1431. if self._inverted_ is None:
  1432. if self._boundary_ in (EJECT, KEEP):
  1433. self._inverted_ = self.__class__(~self._value_)
  1434. else:
  1435. self._inverted_ = self.__class__(self._singles_mask_ & ~self._value_)
  1436. return self._inverted_
  1437. __rand__ = __and__
  1438. __ror__ = __or__
  1439. __rxor__ = __xor__
  1440. class IntFlag(int, ReprEnum, Flag, boundary=KEEP):
  1441. """
  1442. Support for integer-based Flags
  1443. """
  1444. def _high_bit(value):
  1445. """
  1446. returns index of highest bit, or -1 if value is zero or negative
  1447. """
  1448. return value.bit_length() - 1
  1449. def unique(enumeration):
  1450. """
  1451. Class decorator for enumerations ensuring unique member values.
  1452. """
  1453. duplicates = []
  1454. for name, member in enumeration.__members__.items():
  1455. if name != member.name:
  1456. duplicates.append((name, member.name))
  1457. if duplicates:
  1458. alias_details = ', '.join(
  1459. ["%s -> %s" % (alias, name) for (alias, name) in duplicates])
  1460. raise ValueError('duplicate values found in %r: %s' %
  1461. (enumeration, alias_details))
  1462. return enumeration
  1463. def _dataclass_repr(self):
  1464. dcf = self.__dataclass_fields__
  1465. return ', '.join(
  1466. '%s=%r' % (k, getattr(self, k))
  1467. for k in dcf.keys()
  1468. if dcf[k].repr
  1469. )
  1470. def global_enum_repr(self):
  1471. """
  1472. use module.enum_name instead of class.enum_name
  1473. the module is the last module in case of a multi-module name
  1474. """
  1475. module = self.__class__.__module__.split('.')[-1]
  1476. return '%s.%s' % (module, self._name_)
  1477. def global_flag_repr(self):
  1478. """
  1479. use module.flag_name instead of class.flag_name
  1480. the module is the last module in case of a multi-module name
  1481. """
  1482. module = self.__class__.__module__.split('.')[-1]
  1483. cls_name = self.__class__.__name__
  1484. if self._name_ is None:
  1485. return "%s.%s(%r)" % (module, cls_name, self._value_)
  1486. if _is_single_bit(self._value_):
  1487. return '%s.%s' % (module, self._name_)
  1488. if self._boundary_ is not FlagBoundary.KEEP:
  1489. return '|'.join(['%s.%s' % (module, name) for name in self.name.split('|')])
  1490. else:
  1491. name = []
  1492. for n in self._name_.split('|'):
  1493. if n[0].isdigit():
  1494. name.append(n)
  1495. else:
  1496. name.append('%s.%s' % (module, n))
  1497. return '|'.join(name)
  1498. def global_str(self):
  1499. """
  1500. use enum_name instead of class.enum_name
  1501. """
  1502. if self._name_ is None:
  1503. cls_name = self.__class__.__name__
  1504. return "%s(%r)" % (cls_name, self._value_)
  1505. else:
  1506. return self._name_
  1507. def global_enum(cls, update_str=False):
  1508. """
  1509. decorator that makes the repr() of an enum member reference its module
  1510. instead of its class; also exports all members to the enum's module's
  1511. global namespace
  1512. """
  1513. if issubclass(cls, Flag):
  1514. cls.__repr__ = global_flag_repr
  1515. else:
  1516. cls.__repr__ = global_enum_repr
  1517. if not issubclass(cls, ReprEnum) or update_str:
  1518. cls.__str__ = global_str
  1519. sys.modules[cls.__module__].__dict__.update(cls.__members__)
  1520. return cls
  1521. def _simple_enum(etype=Enum, *, boundary=None, use_args=None):
  1522. """
  1523. Class decorator that converts a normal class into an :class:`Enum`. No
  1524. safety checks are done, and some advanced behavior (such as
  1525. :func:`__init_subclass__`) is not available. Enum creation can be faster
  1526. using :func:`simple_enum`.
  1527. >>> from enum import Enum, _simple_enum
  1528. >>> @_simple_enum(Enum)
  1529. ... class Color:
  1530. ... RED = auto()
  1531. ... GREEN = auto()
  1532. ... BLUE = auto()
  1533. >>> Color
  1534. <enum 'Color'>
  1535. """
  1536. def convert_class(cls):
  1537. nonlocal use_args
  1538. cls_name = cls.__name__
  1539. if use_args is None:
  1540. use_args = etype._use_args_
  1541. __new__ = cls.__dict__.get('__new__')
  1542. if __new__ is not None:
  1543. new_member = __new__.__func__
  1544. else:
  1545. new_member = etype._member_type_.__new__
  1546. attrs = {}
  1547. body = {}
  1548. if __new__ is not None:
  1549. body['__new_member__'] = new_member
  1550. body['_new_member_'] = new_member
  1551. body['_use_args_'] = use_args
  1552. body['_generate_next_value_'] = gnv = etype._generate_next_value_
  1553. body['_member_names_'] = member_names = []
  1554. body['_member_map_'] = member_map = {}
  1555. body['_value2member_map_'] = value2member_map = {}
  1556. body['_unhashable_values_'] = []
  1557. body['_member_type_'] = member_type = etype._member_type_
  1558. body['_value_repr_'] = etype._value_repr_
  1559. if issubclass(etype, Flag):
  1560. body['_boundary_'] = boundary or etype._boundary_
  1561. body['_flag_mask_'] = None
  1562. body['_all_bits_'] = None
  1563. body['_singles_mask_'] = None
  1564. body['_inverted_'] = None
  1565. body['__or__'] = Flag.__or__
  1566. body['__xor__'] = Flag.__xor__
  1567. body['__and__'] = Flag.__and__
  1568. body['__ror__'] = Flag.__ror__
  1569. body['__rxor__'] = Flag.__rxor__
  1570. body['__rand__'] = Flag.__rand__
  1571. body['__invert__'] = Flag.__invert__
  1572. for name, obj in cls.__dict__.items():
  1573. if name in ('__dict__', '__weakref__'):
  1574. continue
  1575. if _is_dunder(name) or _is_private(cls_name, name) or _is_sunder(name) or _is_descriptor(obj):
  1576. body[name] = obj
  1577. else:
  1578. attrs[name] = obj
  1579. if cls.__dict__.get('__doc__') is None:
  1580. body['__doc__'] = 'An enumeration.'
  1581. #
  1582. # double check that repr and friends are not the mixin's or various
  1583. # things break (such as pickle)
  1584. # however, if the method is defined in the Enum itself, don't replace
  1585. # it
  1586. enum_class = type(cls_name, (etype, ), body, boundary=boundary, _simple=True)
  1587. for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
  1588. if name not in body:
  1589. # check for mixin overrides before replacing
  1590. enum_method = getattr(etype, name)
  1591. found_method = getattr(enum_class, name)
  1592. object_method = getattr(object, name)
  1593. data_type_method = getattr(member_type, name)
  1594. if found_method in (data_type_method, object_method):
  1595. setattr(enum_class, name, enum_method)
  1596. gnv_last_values = []
  1597. if issubclass(enum_class, Flag):
  1598. # Flag / IntFlag
  1599. single_bits = multi_bits = 0
  1600. for name, value in attrs.items():
  1601. if isinstance(value, auto) and auto.value is _auto_null:
  1602. value = gnv(name, 1, len(member_names), gnv_last_values)
  1603. if value in value2member_map:
  1604. # an alias to an existing member
  1605. member = value2member_map[value]
  1606. redirect = property()
  1607. redirect.member = member
  1608. redirect.__set_name__(enum_class, name)
  1609. setattr(enum_class, name, redirect)
  1610. member_map[name] = member
  1611. else:
  1612. # create the member
  1613. if use_args:
  1614. if not isinstance(value, tuple):
  1615. value = (value, )
  1616. member = new_member(enum_class, *value)
  1617. value = value[0]
  1618. else:
  1619. member = new_member(enum_class)
  1620. if __new__ is None:
  1621. member._value_ = value
  1622. member._name_ = name
  1623. member.__objclass__ = enum_class
  1624. member.__init__(value)
  1625. redirect = property()
  1626. redirect.member = member
  1627. redirect.__set_name__(enum_class, name)
  1628. setattr(enum_class, name, redirect)
  1629. member_map[name] = member
  1630. member._sort_order_ = len(member_names)
  1631. value2member_map[value] = member
  1632. if _is_single_bit(value):
  1633. # not a multi-bit alias, record in _member_names_ and _flag_mask_
  1634. member_names.append(name)
  1635. single_bits |= value
  1636. else:
  1637. multi_bits |= value
  1638. gnv_last_values.append(value)
  1639. enum_class._flag_mask_ = single_bits | multi_bits
  1640. enum_class._singles_mask_ = single_bits
  1641. enum_class._all_bits_ = 2 ** ((single_bits|multi_bits).bit_length()) - 1
  1642. # set correct __iter__
  1643. member_list = [m._value_ for m in enum_class]
  1644. if member_list != sorted(member_list):
  1645. enum_class._iter_member_ = enum_class._iter_member_by_def_
  1646. else:
  1647. # Enum / IntEnum / StrEnum
  1648. for name, value in attrs.items():
  1649. if isinstance(value, auto):
  1650. if value.value is _auto_null:
  1651. value.value = gnv(name, 1, len(member_names), gnv_last_values)
  1652. value = value.value
  1653. if value in value2member_map:
  1654. # an alias to an existing member
  1655. member = value2member_map[value]
  1656. redirect = property()
  1657. redirect.member = member
  1658. redirect.__set_name__(enum_class, name)
  1659. setattr(enum_class, name, redirect)
  1660. member_map[name] = member
  1661. else:
  1662. # create the member
  1663. if use_args:
  1664. if not isinstance(value, tuple):
  1665. value = (value, )
  1666. member = new_member(enum_class, *value)
  1667. value = value[0]
  1668. else:
  1669. member = new_member(enum_class)
  1670. if __new__ is None:
  1671. member._value_ = value
  1672. member._name_ = name
  1673. member.__objclass__ = enum_class
  1674. member.__init__(value)
  1675. member._sort_order_ = len(member_names)
  1676. redirect = property()
  1677. redirect.member = member
  1678. redirect.__set_name__(enum_class, name)
  1679. setattr(enum_class, name, redirect)
  1680. member_map[name] = member
  1681. value2member_map[value] = member
  1682. member_names.append(name)
  1683. gnv_last_values.append(value)
  1684. if '__new__' in body:
  1685. enum_class.__new_member__ = enum_class.__new__
  1686. enum_class.__new__ = Enum.__new__
  1687. return enum_class
  1688. return convert_class
  1689. @_simple_enum(StrEnum)
  1690. class EnumCheck:
  1691. """
  1692. various conditions to check an enumeration for
  1693. """
  1694. CONTINUOUS = "no skipped integer values"
  1695. NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags"
  1696. UNIQUE = "one name per value"
  1697. CONTINUOUS, NAMED_FLAGS, UNIQUE = EnumCheck
  1698. class verify:
  1699. """
  1700. Check an enumeration for various constraints. (see EnumCheck)
  1701. """
  1702. def __init__(self, *checks):
  1703. self.checks = checks
  1704. def __call__(self, enumeration):
  1705. checks = self.checks
  1706. cls_name = enumeration.__name__
  1707. if Flag is not None and issubclass(enumeration, Flag):
  1708. enum_type = 'flag'
  1709. elif issubclass(enumeration, Enum):
  1710. enum_type = 'enum'
  1711. else:
  1712. raise TypeError("the 'verify' decorator only works with Enum and Flag")
  1713. for check in checks:
  1714. if check is UNIQUE:
  1715. # check for duplicate names
  1716. duplicates = []
  1717. for name, member in enumeration.__members__.items():
  1718. if name != member.name:
  1719. duplicates.append((name, member.name))
  1720. if duplicates:
  1721. alias_details = ', '.join(
  1722. ["%s -> %s" % (alias, name) for (alias, name) in duplicates])
  1723. raise ValueError('aliases found in %r: %s' %
  1724. (enumeration, alias_details))
  1725. elif check is CONTINUOUS:
  1726. values = set(e.value for e in enumeration)
  1727. if len(values) < 2:
  1728. continue
  1729. low, high = min(values), max(values)
  1730. missing = []
  1731. if enum_type == 'flag':
  1732. # check for powers of two
  1733. for i in range(_high_bit(low)+1, _high_bit(high)):
  1734. if 2**i not in values:
  1735. missing.append(2**i)
  1736. elif enum_type == 'enum':
  1737. # check for powers of one
  1738. for i in range(low+1, high):
  1739. if i not in values:
  1740. missing.append(i)
  1741. else:
  1742. raise Exception('verify: unknown type %r' % enum_type)
  1743. if missing:
  1744. raise ValueError(('invalid %s %r: missing values %s' % (
  1745. enum_type, cls_name, ', '.join((str(m) for m in missing)))
  1746. )[:256])
  1747. # limit max length to protect against DOS attacks
  1748. elif check is NAMED_FLAGS:
  1749. # examine each alias and check for unnamed flags
  1750. member_names = enumeration._member_names_
  1751. member_values = [m.value for m in enumeration]
  1752. missing_names = []
  1753. missing_value = 0
  1754. for name, alias in enumeration._member_map_.items():
  1755. if name in member_names:
  1756. # not an alias
  1757. continue
  1758. if alias.value < 0:
  1759. # negative numbers are not checked
  1760. continue
  1761. values = list(_iter_bits_lsb(alias.value))
  1762. missed = [v for v in values if v not in member_values]
  1763. if missed:
  1764. missing_names.append(name)
  1765. missing_value |= reduce(_or_, missed)
  1766. if missing_names:
  1767. if len(missing_names) == 1:
  1768. alias = 'alias %s is missing' % missing_names[0]
  1769. else:
  1770. alias = 'aliases %s and %s are missing' % (
  1771. ', '.join(missing_names[:-1]), missing_names[-1]
  1772. )
  1773. if _is_single_bit(missing_value):
  1774. value = 'value 0x%x' % missing_value
  1775. else:
  1776. value = 'combined values of 0x%x' % missing_value
  1777. raise ValueError(
  1778. 'invalid Flag %r: %s %s [use enum.show_flag_values(value) for details]'
  1779. % (cls_name, alias, value)
  1780. )
  1781. return enumeration
  1782. def _test_simple_enum(checked_enum, simple_enum):
  1783. """
  1784. A function that can be used to test an enum created with :func:`_simple_enum`
  1785. against the version created by subclassing :class:`Enum`::
  1786. >>> from enum import Enum, _simple_enum, _test_simple_enum
  1787. >>> @_simple_enum(Enum)
  1788. ... class Color:
  1789. ... RED = auto()
  1790. ... GREEN = auto()
  1791. ... BLUE = auto()
  1792. >>> class CheckedColor(Enum):
  1793. ... RED = auto()
  1794. ... GREEN = auto()
  1795. ... BLUE = auto()
  1796. >>> _test_simple_enum(CheckedColor, Color)
  1797. If differences are found, a :exc:`TypeError` is raised.
  1798. """
  1799. failed = []
  1800. if checked_enum.__dict__ != simple_enum.__dict__:
  1801. checked_dict = checked_enum.__dict__
  1802. checked_keys = list(checked_dict.keys())
  1803. simple_dict = simple_enum.__dict__
  1804. simple_keys = list(simple_dict.keys())
  1805. member_names = set(
  1806. list(checked_enum._member_map_.keys())
  1807. + list(simple_enum._member_map_.keys())
  1808. )
  1809. for key in set(checked_keys + simple_keys):
  1810. if key in ('__module__', '_member_map_', '_value2member_map_', '__doc__'):
  1811. # keys known to be different, or very long
  1812. continue
  1813. elif key in member_names:
  1814. # members are checked below
  1815. continue
  1816. elif key not in simple_keys:
  1817. failed.append("missing key: %r" % (key, ))
  1818. elif key not in checked_keys:
  1819. failed.append("extra key: %r" % (key, ))
  1820. else:
  1821. checked_value = checked_dict[key]
  1822. simple_value = simple_dict[key]
  1823. if callable(checked_value) or isinstance(checked_value, bltns.property):
  1824. continue
  1825. if key == '__doc__':
  1826. # remove all spaces/tabs
  1827. compressed_checked_value = checked_value.replace(' ','').replace('\t','')
  1828. compressed_simple_value = simple_value.replace(' ','').replace('\t','')
  1829. if compressed_checked_value != compressed_simple_value:
  1830. failed.append("%r:\n %s\n %s" % (
  1831. key,
  1832. "checked -> %r" % (checked_value, ),
  1833. "simple -> %r" % (simple_value, ),
  1834. ))
  1835. elif checked_value != simple_value:
  1836. failed.append("%r:\n %s\n %s" % (
  1837. key,
  1838. "checked -> %r" % (checked_value, ),
  1839. "simple -> %r" % (simple_value, ),
  1840. ))
  1841. failed.sort()
  1842. for name in member_names:
  1843. failed_member = []
  1844. if name not in simple_keys:
  1845. failed.append('missing member from simple enum: %r' % name)
  1846. elif name not in checked_keys:
  1847. failed.append('extra member in simple enum: %r' % name)
  1848. else:
  1849. checked_member_dict = checked_enum[name].__dict__
  1850. checked_member_keys = list(checked_member_dict.keys())
  1851. simple_member_dict = simple_enum[name].__dict__
  1852. simple_member_keys = list(simple_member_dict.keys())
  1853. for key in set(checked_member_keys + simple_member_keys):
  1854. if key in ('__module__', '__objclass__', '_inverted_'):
  1855. # keys known to be different or absent
  1856. continue
  1857. elif key not in simple_member_keys:
  1858. failed_member.append("missing key %r not in the simple enum member %r" % (key, name))
  1859. elif key not in checked_member_keys:
  1860. failed_member.append("extra key %r in simple enum member %r" % (key, name))
  1861. else:
  1862. checked_value = checked_member_dict[key]
  1863. simple_value = simple_member_dict[key]
  1864. if checked_value != simple_value:
  1865. failed_member.append("%r:\n %s\n %s" % (
  1866. key,
  1867. "checked member -> %r" % (checked_value, ),
  1868. "simple member -> %r" % (simple_value, ),
  1869. ))
  1870. if failed_member:
  1871. failed.append('%r member mismatch:\n %s' % (
  1872. name, '\n '.join(failed_member),
  1873. ))
  1874. for method in (
  1875. '__str__', '__repr__', '__reduce_ex__', '__format__',
  1876. '__getnewargs_ex__', '__getnewargs__', '__reduce_ex__', '__reduce__'
  1877. ):
  1878. if method in simple_keys and method in checked_keys:
  1879. # cannot compare functions, and it exists in both, so we're good
  1880. continue
  1881. elif method not in simple_keys and method not in checked_keys:
  1882. # method is inherited -- check it out
  1883. checked_method = getattr(checked_enum, method, None)
  1884. simple_method = getattr(simple_enum, method, None)
  1885. if hasattr(checked_method, '__func__'):
  1886. checked_method = checked_method.__func__
  1887. simple_method = simple_method.__func__
  1888. if checked_method != simple_method:
  1889. failed.append("%r: %-30s %s" % (
  1890. method,
  1891. "checked -> %r" % (checked_method, ),
  1892. "simple -> %r" % (simple_method, ),
  1893. ))
  1894. else:
  1895. # if the method existed in only one of the enums, it will have been caught
  1896. # in the first checks above
  1897. pass
  1898. if failed:
  1899. raise TypeError('enum mismatch:\n %s' % '\n '.join(failed))
  1900. def _old_convert_(etype, name, module, filter, source=None, *, boundary=None):
  1901. """
  1902. Create a new Enum subclass that replaces a collection of global constants
  1903. """
  1904. # convert all constants from source (or module) that pass filter() to
  1905. # a new Enum called name, and export the enum and its members back to
  1906. # module;
  1907. # also, replace the __reduce_ex__ method so unpickling works in
  1908. # previous Python versions
  1909. module_globals = sys.modules[module].__dict__
  1910. if source:
  1911. source = source.__dict__
  1912. else:
  1913. source = module_globals
  1914. # _value2member_map_ is populated in the same order every time
  1915. # for a consistent reverse mapping of number to name when there
  1916. # are multiple names for the same number.
  1917. members = [
  1918. (name, value)
  1919. for name, value in source.items()
  1920. if filter(name)]
  1921. try:
  1922. # sort by value
  1923. members.sort(key=lambda t: (t[1], t[0]))
  1924. except TypeError:
  1925. # unless some values aren't comparable, in which case sort by name
  1926. members.sort(key=lambda t: t[0])
  1927. cls = etype(name, members, module=module, boundary=boundary or KEEP)
  1928. return cls
  1929. _stdlib_enums = IntEnum, StrEnum, IntFlag