“
It takes about 10 minutes to read this article.
”
In this article, we will talk about why Python decided not to support the switch statement.
Why do you want to talk about this topic?
Mainly because switch is too common in other languages, but Python does not support it. This uniqueness itself is worthy of attention. Answering this question can also help you see more clearly the concept of Python in programming and understand Python’s grammatical design. In the decision-making process.
In addition to analyzing PEP-275 and PEP-3103 in detail, this article will also introduce the latest developments in Python (PEP-622), that is, the pattern matching syntax that may be introduced. I believe this topic will broaden everyone’s horizons. So as to have a more comprehensive understanding of switch grammar.
Before starting the topic, we need to talk about what switch is?
Some students may think of it for the first time...
Hey~hey~, please take care of yourself, don't always think about the game, we are going to talk 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 express, it looks like this:
Its usage is not difficult to understand: which case condition the value of the switch statement satisfies, the corresponding code block will be executed, and the break will jump out during execution, otherwise it will continue to execute the next case branch; generally a default branch will be placed at the end , As the bottom of the pocket.
Most languages provide switch statements or very similar things. For example, in static languages such as C/C++/Java/Go, they all support switch-case structure; in Ruby there is a similar case-when structure, in Shell In the language, there is a similar case-in structure, in Perl, there is switch-case-else...
The advantage of the switch statement is that it supports the "single condition and multi-branch" selection structure. Compared with the if-else binary selection structure, it will be more concise and clear in some cases.
However, in Python, we can't see switch-case or similar grammatical structure. Why?
There is an FAQ in the official document that contains this question: Why isn't there a switch or case statement in Python?
FAQ stands for Frequently Asked Questions, which means frequently asked questions. The official list of 27 frequently asked questions is here: https://mp.weixin.qq.com/s/zabIvt4dfu_rf7SmGZXqXg
The document gives several suggestions and tells us several switch/case alternatives:
There have been some proposals (ie PEP-275 and PEP-3103) that want to introduce switch syntax to Python. However, there is no consensus on "whether and how to conduct range testing".
Range test, or range test, refers to various tests to verify the technical performance of weapons and ammunition. Like clinical trials of drugs, it is a critical test before the final product is delivered.
The official document's explanation of "Why Python does not introduce switch" actually comes from the opinion of Guido van Rossum, the father of Python, in PEP-3103:
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 at PyCon 2007, and the results showed that this proposal did not receive widespread support. Therefore, I rejected it.
In short, the **PEP proposal is there, and the grammar implementation is in its embryonic form, but the core developers seem to have not reached an agreement, which ultimately leads to the abortion of the proposal. **
PEP-3103 was proposed in 2006, and PEP-275 was proposed in 2001. What they have in common is that they put forward a certain necessity of introducing switch statements and analyzed several alternative implementation schemes. However, , The ending is rejected.
Source: https://www.python.org/dev/peps/pep-0275
So, let's first review what the core developers have made discussions, and see what would happen if Python were to implement the switch structure? (PS: PEP also involves other content, this article only extracts the part 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 does not exist 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 listed some other issues:
In addition to the preferred scheme, the PEP also records several grammatical 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.
It first recognized the two basic settings in PEP-275, for example, the realization of "implicit break", to prevent the case branch from falling-through, which transfers control (other languages seem to require explicit writing break); the else branch is optional, reuse the else keyword instead of introducing "default".
Guido agrees with the style promoted by PEP-275, but he also thinks that its problem is too many levels of indentation. Therefore, it is recommended to reduce the number of spaces in the code branch indentation. For example, the original indentation is 4 spaces, and it is changed to indentation 2. Spaces.
PEP-3103 also lists three other implementation schemes, analyzes their differences and problems, the specific content is omitted, here is just to show you their styles:
# case branch is not indented
switch EXPR:case EXPR:
SUITE
case EXPR:
SUITE
.... else:
SUITE
# No colon after switch statement
switch EXPR
case EXPR:
SUITE
case EXPR:
SUITE
.... else:
SUITE
# Omit the case keyword
switch EXPR:
EXPR:
SUITE
EXPR:
SUITE
... else:
SUITE
In addition to the basic syntax, Guido spent a lot of space discussing the extended syntax (Extended Syntax), that is, the complex situation of matching multiple values in a case branch:
case EXPR, EXPR,...:
# Guido preferred
casein EXPR_LIST:case*EXPR:case[*]EXPR,[*]EXPR,...:case*(EXPR, EXPR,...):
The key issues he considered include: the case where the result of the expression in switch is a tuple or iterable object, the case where the value of the case is treated as a tuple unpacking, and the "*" asterisk operation in the case branch...
Then, Guido spent a lot of space to analyze how to implement switch, the main ideas discussed in it are:
There is a lot of content in this part of the PEP, because Guido also considered several implementation paths for each idea, which led to his conclusion after complex analysis: It is too early to decide (it is too early to decide now) early).
After reading PEP-3103, my overall feeling is: Guido's thoughts are very divergent and rich in layers, but he lacks his "swift knives" insight when facing other problems.
In other words, among the many possible solutions, he strives to cover everything, and ultimately cannot convince himself to make a dictatorial decision. The resistance comes mainly from himself, not from others.
However, the reason for this situation may be related to his default position: He seems to think that "Python is fine without a switch statement", so although he wrote a long PEP, he is only complicating the problem and changing The issue was put on hold.
In the end, he conducted a small survey on PyCon, with which he “justifiably” rejected the PEP he initiated, trying to block everyone’s leisurely mouth...
In the final analysis, the reasons why Python does not have a switch statement are: The implementation details/functions of switch have not been finalized, it is good without a switch, and there are other good ways to replace the little willfulness of switch and Guido......
However, we still have to ask: Will there be a switch statement in the future? Or similar multi-branch selection structure? **
Why is there such a question? The reason is that too many languages have their own switch statements, and many people try to write libraries that provide switch functions (I remember seeing it twice in PyCoder's Weekly).
I (Python cat) didn't like switch from beginning to end. It is almost certain that Python will not have a switch in the future, but it is likely to introduce a more complicated syntax structure similar to switch!
2020 In June 2015, PEP-622 was proposed, which suggested the introduction of pattern matching syntax (pattern matching) in languages such as Scala, Erlang, and Rust.
As of October 2020, the PEP has been broken down into three other PEPs (634-636), all of which are currently in the draft stage. Taking into account the participation of core developers and topic discussions, these proposals are most likely to be implemented in future versions (such as 3.10 under development).
Taking an average function as an example, the 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)/2case[x]: # captures the only element of a sequence
return x
case[]:return0case x: # captures the entire sequence
returnsum(x)/len(x)
The match-case structure is similar to the switch-case structure, but it is based on a pattern rather than an expression, so there are more details to be considered and a broader application space.
Readers interested in this topic are advised to check these new PEPs.
Finally, let us return to the question in the title: **Why doesn't Python support the switch statement? **
The FAQ of the official document has an answer to this question, telling us that there are several good alternatives, and also left a clue: PEP once proposed to introduce switch, but it was not successfully implemented.
Following this clue, this article disassembled the two documents PEP-275 and PEP-3103, showing you the different styles of switch solutions proposed in the Python community, as well as many outstanding issues.
Finally, we also paid attention to the latest PEP-622 development, it seems that the "twin brother" match syntax of switch is expected to be introduced into Python! The discussion on the switch topic seems to be ending, but another larger topic is underway!
Recommended Posts