Why doesn’t Python support switch statements?

Time:2021-2-10

This article is from the “why Python” series. Check outAll articles

In this article, we’ll talk about why Python decided not to support switch statements.

Why do you want to talk about this topic?

The main reason is that switch is too common in other languages, but Python does not support it. This uniqueness itself is worth paying attention to. To answer this question, we can see more clearly the concept of Python in programming design and understand the decision-making process of Python in syntax design.

In addition to the detailed analysis of pep-275 and pep-3103, this article will also introduce the latest development of python (pep-622), that is, the possible introduction of pattern matching syntax. I believe this topic will broaden our horizons, so as to have a more comprehensive understanding of switch syntax.

1. What is switch?

Before we get down to business, we need to talk about what switch is?

Some students may think of it for the first time

Why doesn't Python support switch statements?

Hello ~ Hello ~, please take heart, don’t always think about the game, we are talking about the switch statement in the programming language.

Generally speaking, the syntax format of switch is as follows:

switch(expression){
    case value1:
       //Statement
       Break; // optional
    case value2:
       //Statement
       Break; // optional
    Default: // optional
       //Statement
}

Use the flow chart to show, it’s like this:

Why doesn't Python support switch statements?

Its usage is not difficult to understand: if the value of the switch statement satisfies any case, the corresponding code block will be executed, and it will jump out when it encounters a break, otherwise it will continue to execute the next case branch; generally, a default branch will be put at the end as a cover.

Most languages provide switch statements or extremely similar things. For example, in static languages such as C / C + + / Java / go, they all support switch case structure; in ruby, they have similar case when structure; in shell, they have similar case in structure; in Perl, they have switch case else structure

The advantage of switch statement is that it supports “single condition multi branch” selection structure, which is more concise and clear than if else binary selection structure.

But in Python, we don’t see switch case or similar syntax structure. Why?

2. Why doesn’t Python support switch?

There is a FAQ in the official document that contains this question:Why isn’t there a switch or case statement in Python?

Why doesn't Python support switch statements?

FAQ is the abbreviation of frequently asked questions, which means frequently asked questions. The official list of 27 frequently asked questions is as follows:https://mp.weixin.qq.com/s/zabIvt4dfu_rf7SmGZXqXg

This document gives us several suggestions and tells us several alternatives to switch / case

  • Use if elif else condition to judge statement
  • Use a dictionary to map the case value to the called function
  • Use the built-in getattr() to retrieve specific object calls

There have been some proposals (pep-275 and pep-3103) to introduce switch syntax to python. However, for Python, the“Whether and how to conduct range test”There is no consensus.

Range test, or range test, refers to all kinds of tests and verifications on the technical performance of weapons and ammunition. Like clinical trials of drugs, it is a key test before the delivery of final products.

The explanation of “why Python doesn’t introduce switch” in the official document actually comes from the opinion of Guido van Rossum, the father of python, in pep-3103

Why doesn't Python support switch statements?

source:https://www.python.org/dev/peps/pep-3103/

A quick poll during my keynote presentation at PyCon 2007 shows this proposal has no popular support. I therefore reject it.

I did a quick poll in the keynote speech of pycon 2007, and the results showed that the proposal did not get wide support. So I rejected it.

In short,PEP proposal and syntax implementation have taken shape, but the core developers do not seem to reach an agreement, which eventually leads to the abortion of the proposal.

3. What does pep-275 and pep-3103 say?

Pep-3103 was proposed in 2006, while pep-275 was proposed in 2001. What they have in common is that they proposed the necessity of introducing switch statement and analyzed several alternative implementation schemes. However, they were rejected in the end.

Why doesn't Python support switch statements?

source:https://www.python.org/dev/peps/pep-0275/

So, let’s first review the discussions made by core developers, and see what Python will look like if it wants to implement the switch structure? (PS: PEP also involves other contents, this article only extracts the parts directly related to switch)

The grammatical structure proposed by pep-275 is as follows:

switch EXPR:
    case CONSTANT:
        SUITE
    case CONSTANT:
        SUITE
    ...
    else:
        SUITE

The else branch is optional. If it is not available and the previous branches are not satisfied, nothing will be done. In addition, the case value constant supports different types, because the type of expr expression is dynamic.

Pep-275 also proposes that switch does not support fall through behavior, that is, each case branch is independent and complete, and there is no need to write break like C language.

The PEP also lists some other issues

  • Reuse existing keywords without introducing “switch” and “case”
  • Use new keywords to avoid confusion with C’s switch concept
  • Support single branch multi value selection (for example: case ‘a’, ‘B’, ‘C’:…)
  • It is also suggested to support the range value judgment (for example: case 10.. 14:…)

In addition to the preferred scheme, the PEP also records several syntax schemes with different styles

case EXPR:
    of CONSTANT:
        SUITE
    of CONSTANT:
        SUITE
    else:
        SUITE

case EXPR:
    if CONSTANT:
         SUITE
    if CONSTANT:
        SUITE
    else:
        SUITE

when EXPR:
    in CONSTANT_TUPLE:
        SUITE
    in CONSTANT_TUPLE:
        SUITE
    ...
else:
     SUITE

Pep-275 recorded many important ideas and problems, which paved the way for the emergence of pep-3103.

So let’s take a look at what pep-3103, written by Guido, says.

Firstly, it recognizes two basic settings in pep-275. For example, it implements “implicit break” to prevent the case branch from transferring the control right of false through (other languages seem to require explicit break); else branch is optional, reusing else keyword instead of introducing “default”.

Guido agrees with the style advocated by pep-275, but also thinks that the problem is that there are too many indentation levels. Therefore, it is suggested to reduce the number of spaces indented in code branches. For example, instead of indenting 4 spaces, it should indent 2 spaces.

Pep-3103 also lists three other implementation schemes, and analyzes their differences and problems. The specific content is omitted. Here I just show you their styles:

#Case branch not indented
switch EXPR:
case EXPR:
    SUITE
case EXPR:
    SUITE
....
else:
    SUITE

#Switch statement without colon
switch EXPR
case EXPR:
    SUITE
case EXPR:
    SUITE
....
else:
    SUITE

#Omit case keyword
switch EXPR:
    EXPR:
        SUITE
    EXPR:
        SUITE
    ...
    else:
        SUITE

Apart from the basic syntax, Guido has spent a lot of time discussing extended syntax, that is, the complexity of matching multiple values in a case branch

case EXPR, EXPR, ...:

#Guido preferred
case in EXPR_LIST:

case *EXPR:

case [*]EXPR, [*]EXPR, ...:

case *(EXPR, EXPR, ...):

His key considerations include: when the result of an expression in switch is a tuple or an iteratable object, when the value of case is seen as a metagroup unpacking, and when “*” asterisk operation is performed on the case branch

Then, Guido spent a lot of time to analyze how to realize switch

  • Use equivalent if elif chain to define switch statement (some optimization may be done)
  • In addition, all expressions must be hashable
  • As a pre computed dispatch of dictionaries

There are many contents in this part of PEP, because Guido also considers several implementation paths in each idea, which leads to his conclusion after complex analysis: it is too early to decide.

After reading pep-3103, my overall feeling is: Guido’s ideas are very divergent and rich in levels, but he lacks his insight of “cutting through the mess” when facing other problems.

That is to say, among the many possible schemes, he tried to cover all aspects, and finally could not persuade himself to make a dictatorial decision. The resistance comes mainly from himself, not from others.

However, the reason for this may be related to his preset position: he seems to think that “Python is fine without a switch statement”, so although he has written a long PEP, he is only complicating the problem and shelving the issue.

At last, he did a small-scale investigation on pycon, so as to “justly” refuse his own PEP, and try to block people’s mouths

4. Will there be a switch statement in the future?

To sum up, there is no switch statement in Python for the following reasons:The implementation details / function points of switch have not been finalized. It’s good without switch. There are other good ways to replace the willfulness of switch and Guido

However, we still have to ask:Will there be a switch statement in the future? Or a similar multi branch selection structure?

Why do you ask? The reason is that too many languages come with switch statements, and many people try to write libraries that provide switch functions (I remember in thePyCoder’s WeeklyI’ve seen it twice.

I (Python cat) don’t like switch from beginning to end. It’s almost certain that Python will not have switch in the future. However, it is likely to introduce a more complex syntax structure similar to switch!

In June 2020, pep-622 was proposed, which proposes to introduce pattern matching syntax in Scala, Erlang and rust(pattern matching)。

Why doesn't Python support switch statements?

As of October 2020, the PEP has been broken down into three other peps (634-636), all of which are in the draft stage. Considering the participation of core developers and the discussion of topics, these proposals are likely to be implemented in future versions (such as 3.10 under development).

Taking an average function as an example, pattern matching syntax can be implemented as follows:

def average(*args):
    match args:
        case [x, y]:           # captures the two elements of a sequence
            return (x + y) / 2
        case [x]:              # captures the only element of a sequence
            return x
        case []:
            return 0
        case x:                # captures the entire sequence
            return sum(x) / len(x)

The match case structure is similar to the switch case structure, but it is based on pattern rather than expression, so it has more details to be considered and wider application space.

Readers who are interested in this topic are advised to refer to these new peps.

Finally, let’s go back to the question in the title:Why doesn’t Python support switch statements?

The FAQ of the official document has an answer to this question, which tells us that there are several good alternatives. At the same time, it also leaves a clue: there was a pep proposal to introduce switch, but it didn’t succeed.

Following this clue, this paper disassembles the two documents pep-275 and pep-3103 to show you the different styles of switch schemes proposed in the python community, as well as many outstanding issues.

Finally, we also pay attention to the latest development of pep-622. It seems that switch’s “twin brother” match syntax is expected to be introduced into Python! The discussion of switch seems to be coming to an end, but another bigger topic is in progress!

This article belongs to the “why Python” series (produced by Python cat). This series mainly focuses on the syntax, design and development of python, and tries to show the charm of Python from the “why” questions. All articles will be filed on GitHub, welcome to give a little star, project address:https://github.com/chinesehua…