You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

enum36.py 35 kB

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台