9

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

Alonme
  • 1,364
  • 15
  • 28

1 Answers1

9

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

  • they have all the methods of that type
  • they can be used as that type
  • and, most importantly, they will compare with other instances of that type

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

Alonme
  • 1,364
  • 15
  • 28
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237