]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Enum: add extended AutoNumber example (GH-22349)
authorEthan Furman <ethan@stoneleaf.us>
Tue, 22 Sep 2020 07:05:27 +0000 (00:05 -0700)
committerGitHub <noreply@github.com>
Tue, 22 Sep 2020 07:05:27 +0000 (00:05 -0700)
Doc/library/enum.rst
Misc/ACKS

index 843d961afc4f723a8ecc1e3a2eedb6c3a1e20f26..3e9b1f9db3550f824f8de57ace0c915832b3864f 100644 (file)
@@ -925,6 +925,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 01ee1cb42d39d0da43549cb2be765688ca47c636..e4bd3da6b6c40abf2f6509011ab8fa8160c44ae8 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -1723,6 +1723,7 @@ Févry Thibault
 Lowe Thiderman
 Nicolas M. Thiéry
 James Thomas
+Reuben Thomas
 Robin Thomas
 Brian Thorne
 Christopher Thorne