Settings

Theme

Pattern Matching in Python

github.com

37 points by amosson 5 years ago · 4 comments

Reader

ggm 5 years ago

Always wanted a switch coding style. Now, offered one i am having second thoughts introspecting if my code improves for readability if I use one. I think on balance yes. I've always like this approach to a single value or expression gating choices.

Also wondering about the degenerate forms of fall through alternates, so it's a stack of code optionally run.

There is another link to c code switches and duffs device in hn recently

  • pmart123 5 years ago

    Switch statements can work well from a readability standpoint such as the HTTP error example they use. However, I almost feel it is more Pythonic to use a dictionary instead, collapsing the function into:

    def http_error(status):

      try:
        return HTTP_STATUS_CODES[status]
      except KeyError:
        return "Something else"
    
    Also, method polymorphism always seemed more powerful and intuitive to me than switch statements when the operation is something like:

      multiply(scalar, scalar)
      multiply(vector, scalar)
      multiply(matrix, scalar)
singhrac 5 years ago

Wow I love this. This is one of my favorite features of Rust/OCaml (along with variant types / data-bearing-enums).

I think the latter would help a lot with error handling in particular, not to mention defining protocols.

pansa2 5 years ago

See also the PEPs: https://www.python.org/dev/peps/pep-0634/#abstract

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection