DEV Community

loading...

Python's Enum makes me (a little) angry

jpsca profile image Juan-Pablo S Originally published at jpscaletti.com ・1 min read

Originally published at https://jpscaletti.com/python-enum-makes-me-angry

Python implementation of Enum screams “design by committee” to me. Enums are supposed to work as replacements for constants in a file or even attributes in a class... why on earth printing an item doesn’t return the value?

class Color(Enum):
    FRONT = "#ffaf2e"
    BACK = "#dedede"

>>> str(Color.FRONT)
'Color.FRONT'   # Are you kidding me!??

>>> str(Color.FRONT.value)
'#ffaf2e'   # I'm not amused 😒

The worst/best part is that is super easy to fix. Just with a __str__ method:

class PracticalEnum(Enum):
    def __str__(self):
        return str(self.value)

class Color(PracticalEnum):
    FRONT = "#ffaf2e"
    BACK = "#dedede"

>>> str(Color.FRONT)
'#ffaf2e'   # YEAH SCIENCE! 💪

Now we are talking!

Discussion (2)

pic
Editor guide
Collapse
orenovadia profile image
orenovadia

I agree that the design is weird.
I think that this particular behavior makes more sense when you care more about the identity of the enum members rather than the values they contain as constants.

Note that all the Enum members are auto-magically replaced with instances of the Enum class,which allows for is-instance and identity tests, see example:

def do_something(color: Color):
    assert isinstance(color, Color) # works because enum members are instances
    if color is Color.FRONT: # works because members are unique instances
       ....

If you are looking to provide more information about each member of the enum, check out this example: docs.python.org/3/library/enum.htm...

Collapse
jpsca profile image
Juan-Pablo S Author

I checked out the Planet example. That's really cool. Thanks.