Why doesn't Python have switch-case?

前端 未结 4 1298
遇见更好的自我
遇见更好的自我 2021-01-30 08:17

Please explain why Python does not have the switch-case feature implemented in it.

相关标签:
4条回答
  • 2021-01-30 08:55

    There is literally a section in the docs to answer this. See below:

    Why isn’t there a switch or case statement in Python?

    TL;DR: existing alternatives (dynamic dispatch via getattr or dict.get, if/elif chains) cover all the use cases just fine.

    0 讨论(0)
  • 2021-01-30 08:56

    Update: There is a new proposal under consideration. See PEP 622 Structural Pattern Matching.


    We considered it at one point, but without having a way to declare named constants, there is no way to generate an efficient jump table. So all we would be left with is syntactic sugar for something we could already do with if-elif-elif-else chains.

    See PEP 275 and PEP 3103 for a full discussion.

    Roughly the rationale is that the various proposals failed to live up to people's expections about what switch-case would do, and they failed to improve on existing solutions (like dictionary-based dispatch, if-elif-chains, getattr-based dispatch, or old-fashioned polymorphism dispatch to objects with differing implementations for the same method).

    0 讨论(0)
  • 2021-01-30 09:03
    def f(x):
        return {
            1 : 'output for case 1',
            2 : 'output for case 2',
            3 : 'output for case 3'
        }.get(x, 'default case')   
    

    You can use this as switch case in python and if condition not match it will return default if condition not match

    0 讨论(0)
  • 2021-01-30 09:05

    I remembered in ancient time, an inexperienced Larry Walls said that Perl doesn't need case switch construct because it can be done the same way with: "if - elif - elif .... else". Back then Perl was nothing more but a mere scripting tool for hacker kiddies. Of course, today's Perl has a switch construct.

    It's not unexpected that over some decades later, the new generation kids with their new toys are doomed to repeat the same dumb statement.

    It's all about maturity, boys. It will eventually have a case construct. And when python has matured enough as a programming language, like FORTRAN/Pascal and C and all languages derived from them, it will even have a "goto" statement :)

    BTW. Usually, case switch translated to asm as indirect jump to list of address of respective cases. It's an unconditional jump, means far more efficient than comparing it first (avoiding branch misprediction failure), even in just a couple cases it considered as more efficient. For a dozen or more (up to hundreds in code snippet for a device driver) the advantage of the construct is unquestionable. I guess Larry Walls didn't talk assembly back then.

    0 讨论(0)
提交回复
热议问题