[HN Gopher] What Is the Switch-Case Equivalent in Python?
       ___________________________________________________________________
        
       What Is the Switch-Case Equivalent in Python?
        
       Author : Sami_Lehtinen
       Score  : 27 points
       Date   : 2021-04-03 18:18 UTC (4 hours ago)
        
 (HTM) web link (pakstech.com)
 (TXT) w3m dump (pakstech.com)
        
       | TrianguloY wrote:
       | "Pattern matching is the switch-case equivalent in Python 3.10
       | and newer"
       | 
       | Well, yes, but actually, no.
       | 
       | A switch operator, at least in most other languages, uses
       | comparison to select a branch. Only comparisons are performed
       | (either with each branch or optimized for direct access) but no
       | other side effect. Pattern matching, as with other languages too,
       | tries to 'match' the variable to the pattern. If it succeeds,
       | then the branch is taken and the variables (if any) are assigned,
       | which in python means that they are assigned to the whole current
       | function. This is a big side effect.
       | 
       | And that's the main problem, the variable constants. Once you
       | understand the issue it is relatively easy to fix, but for a
       | newcomer this will probably be a few minutes of searching and
       | debugging.
       | 
       | Python don't have a switch statement, at least not yet, pattern
       | matching is just another similar feature that can be adapted to
       | work similarly, like the chain of elifs and the lambdas
       | dictionary. However if you want to say otherwise...at least give
       | the warning of the constants at the beginning, not at the end.
        
         | heavenlyblue wrote:
         | You can override a comparison operator which means it's
         | potentially unbounded (not simple) exactly the same way as
         | matching is.
        
       | loloquwowndueo wrote:
       | " It will take a long time until any library code can safely
       | adapt this new functionality since Python 3.9 will reach its end
       | of life approximately in October 2025"
       | 
       | Not true - for example, Black had been requiring python 3.6+ even
       | before 3.5 and older were fully deprecated / unsupported.
       | 
       | Just declare the minimum version your library requires in
       | setup.py and let users decide.
        
       | bko wrote:
       | I love how Scala does case match with case classes. You can
       | essentially unpack the attributes of a case class and match on
       | them and put additional guards. Example:
       | 
       | bob match {                 case Person("bob", _) => println("hi
       | bob!")            case _ => println("I don't know you")
       | 
       | }
       | 
       | I think its important that match returns something so you can use
       | outside of a function which this doesn't do.
       | 
       | val greeting = bob match { ... }
       | 
       | I thought it would be a fun exercise to write case classes in
       | python, kind of like an improved immutable data class with a
       | match that returns.
       | 
       | https://mleverything.substack.com/p/scalas-case-class-in-pyt...
        
       | nicoburns wrote:
       | I can't believe languages are still adding switch/match
       | statements (as opposed to expressions). Has it it not filtered
       | through to everyone yet that everything that can possibly be an
       | expression should be?
        
         | gumby wrote:
         | Hey, it's still a new idea, only introduced in 1958. Give
         | people time to adjust!
        
       | dmarchand90 wrote:
       | I'm really worried for the long term health of python.
       | 
       | The philosophy of python is there should be only one pythonic way
       | of doing things.
       | 
       | But more and more features are being added that give too many
       | options with minor benefit
       | 
       | How is case different from the elif pattern? What does the walrus
       | operator do that we really need.
       | 
       | Each one of these things on their own if fine but I'm worried
       | together it's going to make python increasingly idiosyncratic to
       | each developer and, consequently, harder to read.
       | 
       | Python's Zen beat out perl's TMTOWTDI. But python seems to try to
       | be more and more like perl with every release: more appealing to
       | hackers playing code golf than long term _readers_ of the code
       | base
        
         | neolog wrote:
         | The walrus operator was definitely a mistake. But type
         | annotations, pattern matching, attrs/dataclasses, and f-strings
         | are significant improvements.
        
           | jsmeaton wrote:
           | See though, this is the issue. What you see as a useful or
           | mistaken feature is likely a different set to another user,
           | just as we've seen above.
           | 
           | I think it's a mistake to defer to the zen of python without
           | considering the PEPs themselves which do discuss trade offs.
           | (I'll note that you didn't make that claim but GP did).
        
             | neolog wrote:
             | Tbh I think a consensus of expert Pythonistas would agree
             | with me. Walrus only got through because of the
             | "dictatorship".
        
               | jsmeaton wrote:
               | Perhaps :)
               | 
               | That's not a hill I'm willing to die on but I agree with
               | the positives from your list.
               | 
               | And the small handful of times I've used walrus have been
               | nice, but not game changing.
        
               | musingsole wrote:
               | Language features of this type should be nice and not
               | game changing. It's how spoken word languages evolve. If
               | every change was game-changing, it'd only be a few
               | mutations until a dialect became a language in its own
               | right. In reality, you get countless dialects frequently
               | with features that eventually die off and new languages
               | rarely and only in the aggregate.
        
               | GeorgeTirebiter wrote:
               | Seems to me the 'sweet spot' for a language is a careful
               | balance of continuing to evolve - slowly, carefully - and
               | to not become so large as to 'not fit into one head'.
               | Python3.9 is not yet at the 'too big for one head'; but
               | 3.xx could be. Perhaps old-style features need to be
               | removed, and only available via some sort of "from
               | __past__ import old-feature-set"
        
               | neolog wrote:
               | They could just deprecate without removing.
        
               | musingsole wrote:
               | It's hard for me to separate a language from what it is
               | used to accomplish, and from that perspective, Python has
               | been far too large to fit in one head for a good long
               | time. Perhaps that is why I don't find any compulsion for
               | language purity.
        
         | at_a_remove wrote:
         | Right there with you!
         | 
         | I get it, languages have to grow or fix mistakes. I read
         | _about_ Python long before I attempted to program in it and
         | even I (not a language designer or that special) knew that
         | their handling of division as being integer division as a
         | default was a long-term problem that would eventually be
         | changed one way or another. And so it was.
         | 
         | I absolutely agree on the walrus operator. It's too terse and
         | while on its own it only makes two steps into one, it's not
         | used alone, making each line of code with it that much harder
         | to unpack.
         | 
         | I don't know enough about pattern matching but my feeling is
         | that we got along without it so far ...
        
         | G3rn0ti wrote:
         | Yeah, Perl's been there a long time ago. Initially, Perl did
         | not have a native switch/case statement. However, early on
         | Perlers started to obsess about emulated switch constructs and
         | so Perl 5.10 shipped given/when which was supposed to become
         | the language's official switch implementation. But it never
         | really quite took of. While part of it was due to a subtle bug
         | I'd argue nobody actually needed it. 99% of the time
         | if/elsif/else is good enough and otherwise you might want to
         | consider a dispatch table if the number of cases is large.
         | Beyond Perl this is true in most languages: If you find
         | yourself in a situation to need an extensive if/else chain and
         | to wish for C-like switch/case you're either writing a parser
         | or you should really rethink about your software's architecture
         | (maybe in terms of OOP).
        
         | andi999 wrote:
         | So what is the current one and only one pythonic way when you
         | need a switch statement (like having a lot of cases to handle).
         | I see two possibilities:
         | 
         | 1.a lot of 'if'-statement 2.using a dict and the value is a
         | function you call if the key matches
         | 
         | Or what else?
        
           | roboticmind wrote:
           | I'm not sure that the second option is a very pythonic way to
           | do it, but that's subjective of course. I'd imagine the
           | original commenter views using a lot of ifs and elifs as the
           | pythonic way to do it
        
           | extradesgo wrote:
           | I have used this dict solution before in scripts and I am not
           | proud of it.
        
           | klyrs wrote:
           | There's one that's even closer to c-like switches: a
           | list/tuple of functions or values, indexed by a small int. If
           | you're feeling extremely cheeky, it can even handle negative
           | cases. You'll have to implement fallthrough yourself, though.
        
       | vram22 wrote:
       | Just _for_ fun, and not meant as an exact _match_ (pun noticed
       | :), I had written a simple simulation of C 's switch statement in
       | Python, a _while_ ago:
       | 
       | Simulating the C switch statement in Python:
       | 
       | https://jugad2.blogspot.com/2016/12/simulating-c-switch-stat...
        
       | xchaotic wrote:
       | So switch like statements and branched execution are the enemy of
       | caches and especially in the light of recent CPU predictive
       | execution vulnerabilities I guess that is not an ideal syntax.
       | What's a better way to guide the programs flow based on some
       | input?
        
       ___________________________________________________________________
       (page generated 2021-04-03 23:01 UTC)