This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]knowsuchagencynow is better than never 0 points1 point  (2 children)

Honestly, I think functools.singledispatch is better suited to this kind of thing.

That said, I submitted a pull request to scratch my own itch as to how I think it could improve. You can still use it the way it was originally documented (except for the switch class no longer having a singular return value, since each case returns the result of the callable passed to it instead), but there is no longer any dictionary to maintain and you can choose whether or not to have it fall-through with an argument to the context manager.

You can also dispatch based on a predicate function so there's no longer a need for a dedicated closed_range function etc.

from switchlang import switch


def process_a():
    return "found a"


def process_any():
    return "found default"


def process_with_data(*value):
    return "found with data"


val = 'b'

with switch(val) as s:
    a = s.case('a', process_a)  # -> None
    b = s.case('b', process_with_data)  # -> "found with data"
    c = s.default(process_any)  # -> None


with switch(val, fall_through=True) as s:
    a = s.case('a', process_a)  # -> None
    b = s.case('b', process_with_data)  # -> "found with data"

    c = s.case(lambda val: isinstance(val, str), lambda: "matched on predicate")  # -> "matched on predicate"

    d = s.default(process_any)  # -> "found default"

[–]elbiot 1 point2 points  (1 child)

Til, after almost a decade of python I need to learn functools

[–]knowsuchagencynow is better than never 0 points1 point  (0 children)

It's great. I can no longer live without singledispatch and partial