Skip to main content

Switch-case statement for Python

Project description

switch_case

License Codecov PyPI Python Version

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

Uploaded source

Built Distribution

switch_case-1.5-py3-none-any.whl (8.0 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page