Skip to content

Commit

Permalink
bpo-37062: Enum: add extended AutoNumber example (GH-22349) (GH-22369)
Browse files Browse the repository at this point in the history
(cherry picked from commit 62e40d8)

Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
  • Loading branch information
miss-islington and ethanfurman committed Sep 23, 2020
1 parent 2466a7a commit 5acc1b5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Doc/library/enum.rst
Expand Up @@ -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::

Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Expand Up @@ -1678,6 +1678,7 @@ Févry Thibault
Lowe Thiderman
Nicolas M. Thiéry
James Thomas
Reuben Thomas
Robin Thomas
Brian Thorne
Christopher Thorne
Expand Down

0 comments on commit 5acc1b5

Please sign in to comment.