Skip to main content

switchcase implements a simple Switch-Case construct in Pure Python.

Under the hood, the switch function works by simply returning a length-1 list containing a matching function. The entire implementation is 3 lines long:

from operator import eq
def switch(value, comp=eq):
    return [lambda match: comp(match, value)]

Basic Usage

>>> from switchcase import switch
>>> def func(x):
...     for case in switch(x):
...         if case(0):
...             print("x was 0")
...             break
...         if case(1):
...             print("x was 1")
...             break
...     else:
...         print("x was unmatched")
>>> func(0)
"x was 0"
>>> func(1)
"x was 1"
>>> func(2)
"x was unmatched"

Custom Comparisons

By default, switch uses operator.eq to compare the value passed to switch and the values subsequently passed to case. You can override this behavior by passing a comparator function to switch as a second argument.

>>> import re
>>> from switchcase import switch
>>> def f(x):
...     out = []
...     for case in switch(x, comp=re.match):
...         if case("foo_bar"):
...             out.append(0)
...             break
...         if case("foo_.*"):
...             out.append(1)
...         if case(".*_bar"):
...             out.append(2)
...         return out
>>> f("foo_bar")
[0]
>>> f("foo_notbar")
[1]
>>> f("notfoo_bar")
[2]
>>> f("foo____bar")
[1, 2]

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

switchcase-1.0.tar.gz (2.2 kB view details)

Uploaded Source

File details

Details for the file switchcase-1.0.tar.gz.

File metadata

  • Download URL: switchcase-1.0.tar.gz
  • Upload date:
  • Size: 2.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for switchcase-1.0.tar.gz
Algorithm Hash digest
SHA256 4170300a2e69611cff996e508fb3a2d3caff257f44f70c987dbfe3500b722e72
MD5 0e1424a4a4d7f5c79c1694c5ce200c22
BLAKE2b-256 010844a3d89b53d8d43266126584821bc08e0b3d0e95a2025fed3ec3bd7ab5b1

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.0

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page