:meth:`__add__`, etc.), descriptors (methods are also descriptors), and
variable names listed in :attr:`_ignore_`.
-Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__` then
+Note: if your enumeration defines :meth:`__new__` and/or :meth:`__init__`,
any value(s) given to the enum member will be passed into those methods.
See `Planet`_ for an example.
+.. note::
+
+ The :meth:`__new__` method, if defined, is used during creation of the Enum
+ members; it is then replaced by Enum's :meth:`__new__` which is used after
+ class creation for lookup of existing members. See :ref:`new-vs-init` for
+ more details.
+
Restricted Enum subclassing
---------------------------
:meth:`__str__` method has been reset to their data types'
:meth:`__str__` method.
+.. _new-vs-init:
+
When to use :meth:`__new__` vs. :meth:`__init__`
------------------------------------------------
>>> print(Coordinate(3))
Coordinate.VY
+.. warning::
+
+ *Do not* call ``super().__new__()``, as the lookup-only ``__new__`` is the one
+ that is found; instead, use the data type directly.
+
Finer Points
^^^^^^^^^^^^
members; it is then replaced by Enum's :meth:`__new__` which is used after
class creation for lookup of existing members.
+.. warning::
+
+ *Do not* call ``super().__new__()``, as the lookup-only ``__new__`` is the one
+ that is found; instead, use the data type directly -- e.g.::
+
+ obj = int.__new__(cls, value)
+
OrderedEnum
^^^^^^^^^^^
value = first_enum._generate_next_value_(name, start, count, last_values[:])
last_values.append(value)
names.append((name, value))
+ if names is None:
+ names = ()
# Here, names is either an iterable of (name, value) or a mapping.
for item in names:
for member in cls._member_map_.values():
if member._value_ == value:
return member
+ # still not found -- verify that members exist, in-case somebody got here mistakenly
+ # (such as via super when trying to override __new__)
+ if not cls._member_map_:
+ raise TypeError("%r has no members defined" % cls)
+ #
# still not found -- try _missing_ hook
try:
exc = None
with self.assertRaises(AttributeError):
del Season.SPRING.name
+ def test_bad_new_super(self):
+ with self.assertRaisesRegex(
+ TypeError,
+ 'has no members defined',
+ ):
+ class BadSuper(self.enum_type):
+ def __new__(cls, value):
+ obj = super().__new__(cls, value)
+ return obj
+ failed = 1
+
def test_basics(self):
TE = self.MainEnum
if self.is_flag: