Skip to content

Commit 64362c2

Browse files
bpo-37062: Enum: add extended AutoNumber example (GH-22349) (GH-22370)
(cherry picked from commit 62e40d8) Co-authored-by: Ethan Furman <[email protected]>
1 parent f27a157 commit 64362c2

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Doc/library/enum.rst

+26
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,32 @@ Using an auto-numbering :meth:`__new__` would look like::
887887
>>> Color.GREEN.value
888888
2
889889

890+
To make a more general purpose ``AutoNumber``, add ``*args`` to the signature::
891+
892+
>>> class AutoNumber(NoValue):
893+
... def __new__(cls, *args): # this is the only change from above
894+
... value = len(cls.__members__) + 1
895+
... obj = object.__new__(cls)
896+
... obj._value_ = value
897+
... return obj
898+
...
899+
900+
Then when you inherit from ``AutoNumber`` you can write your own ``__init__``
901+
to handle any extra arguments::
902+
903+
>>> class Swatch(AutoNumber):
904+
... def __init__(self, pantone='unknown'):
905+
... self.pantone = pantone
906+
... AUBURN = '3497'
907+
... SEA_GREEN = '1246'
908+
... BLEACHED_CORAL = () # New color, no Pantone code yet!
909+
...
910+
>>> Swatch.SEA_GREEN
911+
<Swatch.SEA_GREEN: 2>
912+
>>> Swatch.SEA_GREEN.pantone
913+
'1246'
914+
>>> Swatch.BLEACHED_CORAL.pantone
915+
'unknown'
890916

891917
.. note::
892918

Misc/ACKS

+1
Original file line numberDiff line numberDiff line change
@@ -1713,6 +1713,7 @@ Févry Thibault
17131713
Lowe Thiderman
17141714
Nicolas M. Thiéry
17151715
James Thomas
1716+
Reuben Thomas
17161717
Robin Thomas
17171718
Brian Thorne
17181719
Christopher Thorne

0 commit comments

Comments
 (0)