Skip to main content

Ralsina.Me — Roberto Alsina's website

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­up.py 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­i.org/pro­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)

print(switch(Color.RED))

Apple

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 :-)

Episodio 29: Python Moderno 1: Poetry.

Primera parte de una se­rie mostran­do her­ramien­tas nuevas que reem­plazan cosas vie­jas con al­go mejor. En este video: po­et­ry, reem­plazan­do set­up.py!


Contents © 2000-2024 Roberto Alsina