[Python-checkins] bpo-37062: Enum: add extended AutoNumber example (GH-22349) (GH-22370)

Miss Islington (bot) webhook-mailer at python.org
Tue Sep 22 23:58:39 EDT 2020


https://github.com/python/cpython/commit/64362c2e435eddc5e84cea313d92bc0b96d227f7
commit: 64362c2e435eddc5e84cea313d92bc0b96d227f7
branch: 3.9
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2020-09-22T20:58:32-07:00
summary:

bpo-37062: Enum: add extended AutoNumber example (GH-22349) (GH-22370)

(cherry picked from commit 62e40d8450b9c78346ec3617de7fe3f0ad381510)

Co-authored-by: Ethan Furman <ethan at stoneleaf.us>

files:
M Doc/library/enum.rst
M Misc/ACKS

diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst
index 5f0762edc2590..a3c51655576ba 100644
--- a/Doc/library/enum.rst
+++ b/Doc/library/enum.rst
@@ -887,6 +887,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::
 
diff --git a/Misc/ACKS b/Misc/ACKS
index 5e0953ae91b18..a16f15a74ebdc 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -1713,6 +1713,7 @@ Févry Thibault
 Lowe Thiderman
 Nicolas M. Thiéry
 James Thomas
+Reuben Thomas
 Robin Thomas
 Brian Thorne
 Christopher Thorne



More information about the Python-checkins mailing list