pythonpython-3.xenums

How to extend Python Enum?


Is it possible to extend classes created using the new Enum functionality in Python 3.4? How?

Simple subclassing doesn't appear to work. An example like

from enum import Enum

class EventStatus(Enum):
   success = 0
   failure = 1

class BookingStatus(EventStatus):
   duplicate = 2
   unknown = 3

will give an exception like TypeError: Cannot extend enumerations or (in more recent versions) TypeError: BookingStatus: cannot extend enumeration 'EventStatus'.

How can I make it so that BookingStatus reuses the enumeration values from EventStatus and adds more?


Solution

  • Subclassing an enumeration is allowed only if the enumeration does not define any members.

    Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances.

    https://docs.python.org/3/howto/enum.html#restricted-enum-subclassing

    So no, it's not directly possible.