pythonpython-3.xenumsmultiple-inheritance

What are the caveats of inheriting from both str and Enum


What are the caveats (if any) of using a class that inherits from both str and Enum?

This was listed as a possible way to solve the problem of Serialising an Enum member to JSON

from enum import Enum

class LogLevel(str, Enum):
    DEBUG = 'DEBUG'
    INFO = 'INFO'

Of course the point is to use this class as an enum, with all its advantages


Solution

  • When inheriting from str, or any other type, the resulting enum members are also that type. This means:

    That last point is the most important: because LogLevel.DEBUG is a str it will compare with other strings -- which is good -- but will also compare with other str-based Enums -- which could be bad.

    Info regarding subclassing enum from the documentation