Skip to content

Commit 5acc1b5

Browse files
bpo-37062: Enum: add extended AutoNumber example (pythonGH-22349) (pythonGH-22369)
(cherry picked from commit 62e40d8) Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
1 parent 2466a7a commit 5acc1b5

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Doc/library/enum.rst

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,32 @@ Using an auto-numbering :meth:`__new__` would look like::
888888
>>> Color.GREEN.value
889889
2
890890

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

892918
.. note::
893919

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1678,6 +1678,7 @@ Févry Thibault
16781678
Lowe Thiderman
16791679
Nicolas M. Thiéry
16801680
James Thomas
1681+
Reuben Thomas
16811682
Robin Thomas
16821683
Brian Thorne
16831684
Christopher Thorne

0 commit comments

Comments
 (0)