An Enum-based implementation of switch for Python.
Project description
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()
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!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
enum_switch-0.1.0.tar.gz
(2.2 kB
view details)
Built Distribution
File details
Details for the file enum_switch-0.1.0.tar.gz
.
File metadata
- Download URL: enum_switch-0.1.0.tar.gz
- Upload date:
- Size: 2.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.0.5 CPython/3.8.1 Linux/5.5.8-1-MANJARO
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 77b47ec72d435a812225ba9ff92dd3f83ed9f5d2d75c987f81005075bc43aba8 |
|
MD5 | 2b4a79a8ef274b362e6477e9aad53447 |
|
BLAKE2b-256 | 8bd381f9da74d8ae4f1406bf0d3cb9451d543bffb037463badf71d2a3f1bd7b9 |
File details
Details for the file enum_switch-0.1.0-py3-none-any.whl
.
File metadata
- Download URL: enum_switch-0.1.0-py3-none-any.whl
- Upload date:
- Size: 2.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.0.5 CPython/3.8.1 Linux/5.5.8-1-MANJARO
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | fe00b2fb755b8638104c1a4a37917b7e7aff1b6f1c756a7e732135a5021369f4 |
|
MD5 | 7f10c8fe61b5a93e65c3fc756bff58b0 |
|
BLAKE2b-256 | fca54eee59949ae54502ad341ca5f63852084ad4793b0a13ce6bbee28a0b92b4 |