3

Rather than NewBreakfast-style enums, suppose that in a project you still have OldBreakfast-style enums, leftovers from Python2 days.

from enum import Enum


class OldBreakfast:
    HAM = 0x00
    EGGS = 0x01
    PANCAKES = 0x02


class NewBreakfast(Enum):
    HAM = 0x00
    EGGS = 0x01
    PANCAKES = 0x02


def eat():
    food1 = OldBreakfast.HAM
    food2 = NewBreakfast.HAM
    print(food1)
    print(food2)


eat()

As we see from eat()ing in the code above, one benefit of moving from "old" to "new" is that while single-stepping or, here, printing, one can see what one is eating, rather than have to go back to the code and reverse-map the codes.

Pleasantly, updating the enums to the new style involves a very limited manipulation. In particular, only the definition itself is necessary. Everything else will work by magic.

Is this last statement indeed accurate? Are there traps that one needs to watch out for?

Related: PEP435 1 2 3 4 5

Calaf
  • 10,113
  • 15
  • 57
  • 120

2 Answers2

2

When replacing old code you may need to use IntEnum instead (or StrEnum or ...). For example:

>>> OldBreakfast.HAM == 0
True

>>> NewBreakfast.HAM == 0
False

but:

>>> IntBreakfast.HAM == 0
True
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • I see. Nice. But I'd say that any instances of testing against a constant is a flaw in the code, and it would be a good chance to reveal them to remove them, and in that sense NewBreakfast has an advantage, if an odd one, in that one would have a crying chance of finding where they are, hopefully by a failing test rather than an obscure crash. – Calaf Jul 02 '19 at 23:34
0

Code such as the one in OldBreakfast in the question is perfectly legal, but there is a compelling reason to upgrade one's code to the NewBreakfast style of programming: the ease of debugging.

A snapshot illustrates it best. After setting a breakpoint in PyCharm, the value of the enum is more informative if we have derived from Enum.

Deriving from Enum informs us of the definition

Seeing food2: NewBreakfast.HAM means we do not have to look back at the code, which is necessary with food1: 0.

Calaf
  • 10,113
  • 15
  • 57
  • 120