GitXplorerGitXplorer
r

enum_switch

public
20 stars
2 forks
0 issues

Commits

List of commits on branch master.
Unverified
339a3ed3416ae02a0e2770191c8af0c0b01b94bd

Merge branch 'master' of github.com:ralsina/enum_switch

rralsina committed 5 years ago
Unverified
a01d2d70913910c9897f858915bacf0ca804e0cd

Remove pyc files, Fix #2

rralsina committed 5 years ago
Verified
3de648ce58b5e179bfb20474d1612d915f443f72

Update README.md

rralsina committed 5 years ago
Unverified
e4ac11430a66d17f6c29e99425f2a5b93c816214

Added lockfile

rralsina committed 5 years ago
Unverified
10210554a57d0712d67518abff86a2831cb44f25

MD tweak

rralsina committed 5 years ago
Unverified
781f045f91aafbfff58fdca5f9afd6cc4d4745fa

Done, I think

rralsina committed 5 years ago

README

The README file for this repository.

Enum-based Switch for Python

This is an attempt at creating a way to do a reliable, not-bug-prone implementation, for Python, of a switch thing like other languages have.

How it works

Suppose you have an enum, like this:

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

And you want to implement logic which branches based on a value which is of type Color. You can do it by subclassing the Switch class. The syntax should be obvious, but:

  • Inherit from Switch
  • Implement a method for each value of the Enum
  • If you are not implementing them all: add a default method.
  • If you leave any Enum value unaccounted for: it will raise an exception when you instantiate your class.

Then:

  • Instantiate your class
  • Call it as a function passing it a value from the Enum
  • The respective method will be executed and its return value returned
from enum_switch import Switch

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

And that's it.

Some additional notes:

  • Passing it something that is not a value of the correct Enum type will raise ValueError
  • default is optional

Hope someone finds it useful!