What are the caveats of inheriting from both str and Enum

Viewed 1644

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

2 Answers

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

This approach would work when the Enum Constants are always String. If you are expecting the right hand to be always a string value of the constant, this works.

Here is one example, this would not work if I want the rightHandside to be encoded as an integer

   class Status(str, Enum):
       DEFAULT=1

   type(json.dumps(Status.DEFAULT)  

would output as

Related