Skip to main content

Ralsina.Me — Roberto Alsina's website

Posts about python (old posts, page 107)

Episodio 34: Python moderno 5: 1,2,3,4 ... Probando Enums!

Enums en Python ni siquiera son tan nuevos, es­tán des­de Python 3.4 pero SE US­AN DE­MASI­A­DO POCO.

Y es una pe­na, porque per­miten re­solver mu­chos prob­le­mas de man­era más ro­bus­ta que lo que sea que es­tás ha­cien­do aho­ra. In­cluye un ejem­p­lo de un "switch" basa­do en enum­s.

enum_switch: a enum-based switch thing for Python

I am do­ing a se­ries of videos (s­pan­ish on­ly!) about "mod­ern Python", show­ing the mod­ern re­place­ments for things that are ... dense in their orig­i­nal form­s.

So, I showed Po­et­ry as an al­ter­na­tive to writ­ing your set­ and Click as a way to do things eas­i­er than arg­parse, and Path­lib in­stead of os­.­path and then I want­ed to show Enum­s. Which are not so new since they have been there since Python 3.4 but I feel they are not used wide­ly enough.

And then I no­ticed that they help do a "safer" ver­sion of the clas­si­cal Python ver­sion of C's switch / case where you can be sure of not leav­ing any val­ues un­han­dled.

So, I wrote a lit­tle thing and pushed it to PyP­I: http­s://pyp­­jec­t/enum-switch/

It's a tiny pro­jec­t, but here's an ex­am­ple of how you use it.

from enum import Enum
from enum_switch import Switch

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

class MySwitch(Switch):
    def RED(self):
        return "Apple"

    def GREEN(self):
        return "Kiwi"

    def BLUE(self):
        return "Sky"

switch = MySwitch(Color)



If MySwitch was miss­ing one of those "han­dler­s" for the Enum val­ues? That's an ex­cep­tion. If you don't want to de­fine them al­l? Do a de­fault­() there.

I like this so­lu­tion, but am very in­ter­est­ed to know if some­one has come up with a bet­ter one? Com­ments are en­abled, feel free to tell me :-)

Contents © 2000-2024 Roberto Alsina