Switch-case statement for Python
Project description
switch_case
In Python 3.10 you can use Structural Pattern Matching
Installation
pip3 install switch_case
Usage
from switch_case import *
reason = (
switch
| case(_ == 200) >> 'OK'
| case(_ == 500) >> 'ERROR'
| default >> 'UNKNOWN')
assert reason(200) == 'OK'
assert reason(500) == 'ERROR'
assert reason(400) == 'UNKNOWN'
Which is syntax sugar for:
from switch_case import *
from operator import eq
reason = (
switch
| case(_ /eq/ 200) >> 'OK'
| case(_ /eq/ 500) >> 'ERROR'
| default >> 'UNKNOWN')
So you can use it like this:
from switch_case import *
get_type = (
switch
| case(_ /isinstance/ str) >> "string"
| case(_ /isinstance/ int) >> "integer"
| case(_ /isinstance/ float) >> "float"
| case(_ /isinstance/ bool) >> "bool"
| default >> "other")
Or as a function:
from switch_case import *
def get_type(smth):
return ~(
switch(smth)
| case(_ /isinstance/ str) >> "string"
| case(_ /isinstance/ int) >> "integer"
| case(_ /isinstance/ float) >> "float"
| case(_ /isinstance/ bool) >> "bool"
| default >> "other")
assert get_type(42) == "integer"
assert get_type("42") == "string"
assert get_type(3.14) == "float"
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
switch_case-1.5.tar.gz
(5.3 kB
view details)
Built Distribution
File details
Details for the file switch_case-1.5.tar.gz
.
File metadata
- Download URL: switch_case-1.5.tar.gz
- Upload date:
- Size: 5.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ab5a6e75ab8c704b6870bf99d7c47b355466ab4405c9483928e2e42dce3bdcfa |
|
MD5 | a8a75bb3ce9a24c38add60cf88b6e7ea |
|
BLAKE2b-256 | b086d14bca6c35c4e420d77e533c3adfc113c0662a530abb2c263974f919d06c |
File details
Details for the file switch_case-1.5-py3-none-any.whl
.
File metadata
- Download URL: switch_case-1.5-py3-none-any.whl
- Upload date:
- Size: 8.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a21fba060fbc1060ba61b8a707fcac1173ec4b85b746196fd01655cf77ba4cc5 |
|
MD5 | 701caa98567ce080696bd23891ae2514 |
|
BLAKE2b-256 | bd50c83862f0c838a1eff36c96f10ea7f474332aba9c986f112b4b0d8c83c557 |