]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-37062: Enum: add extended AutoNumber example (GH-22349) (GH-22369)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 23 Sep 2020 03:57:48 +0000 (20:57 -0700)
committerGitHub <noreply@github.com>
Wed, 23 Sep 2020 03:57:48 +0000 (20:57 -0700)
(cherry picked from commit 62e40d8450b9c78346ec3617de7fe3f0ad381510)

Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
Doc/library/enum.rst
Misc/ACKS

index 8753416a27416fea13f01494a9cc0184a5c468c7..bd10016b937b41682c235b3887de5a38258ac43a 100644 (file)
@@ -888,6 +888,32 @@ Using an auto-numbering :meth:`__new__` would look like::
     >>> Color.GREEN.value
     2
 
+To make a more general purpose ``AutoNumber``, add ``*args`` to the signature::
+
+    >>> class AutoNumber(NoValue):
+    ...     def __new__(cls, *args):      # this is the only change from above
+    ...         value = len(cls.__members__) + 1
+    ...         obj = object.__new__(cls)
+    ...         obj._value_ = value
+    ...         return obj
+    ...
+
+Then when you inherit from ``AutoNumber`` you can write your own ``__init__``
+to handle any extra arguments::
+
+    >>> class Swatch(AutoNumber):
+    ...     def __init__(self, pantone='unknown'):
+    ...         self.pantone = pantone
+    ...     AUBURN = '3497'
+    ...     SEA_GREEN = '1246'
+    ...     BLEACHED_CORAL = () # New color, no Pantone code yet!
+    ...
+    >>> Swatch.SEA_GREEN
+    <Swatch.SEA_GREEN: 2>
+    >>> Swatch.SEA_GREEN.pantone
+    '1246'
+    >>> Swatch.BLEACHED_CORAL.pantone
+    'unknown'
 
 .. note::
 
index eee6b9accaa50f8f6fbf464c63570907d360d1ac..8d355da8fde055aef1d0239139926d7e77fb1485 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -1678,6 +1678,7 @@ Févry Thibault
 Lowe Thiderman
 Nicolas M. Thiéry
 James Thomas
+Reuben Thomas
 Robin Thomas
 Brian Thorne
 Christopher Thorne