In this article in the Python Tutorial column, 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 deserves attention, and answering this question can also give a clearer understanding of Python’s programming philosophy. , understand Python’s decision-making process in syntax design.
In addition to analyzing PEP-275 and PEP-3103 in detail, this article will also introduce the latest development trends of Python (PEP-622), that is, the pattern matching syntax that may be introduced. I believe this topic It will broaden everyone's horizons and give them a more comprehensive understanding of switch syntax.
1. What is switch?
Before we get started, we need to talk about what switch is?
Some students may think of it immediately...
Hey~Hey~, please calm down, don’t always think about the game, we What I am talking about is the switch statement in programming languages.
Generally speaking, the syntax format of switch is as follows:
switch(expression){ case value1: // 语句 break; // 可选 case value2: // 语句 break; // 可选 default: // 可选 // 语句}复制代码
Using a flow chart to represent it, it probably looks like this:
It The usage of As a cover.
Most languages provide switch statements or something very similar. For example, in static languages such as C/C/Java/Go, they all support switch-case structures; in Ruby there is a similar case -when structure, in the Shell 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 multiple branches" selection structure , compared to the binary selection structure of if-else, it will be more concise and clearer at some times.
However, in Python, we cannot see switch-case or similar grammatical structures. Why is this?
2. Why doesn't Python support switch?
There is an FAQ in the official documentation that covers this question: Why isn't there a switch or case statement in Python?
FAQ is the abbreviation of Frequently Asked Questions, which means frequently asked questions. The official list of 27 frequently asked questions is here: mp.weixin.qq.com/s/zabIvt4df…
The document gives several suggestions and tells us several switch/case alternatives:
- Use if-elif-else conditional judgment statements
- Use a dictionary to map the case value to the called function
- Use the built-in getattr() to retrieve the specific object call method
Some proposals have been made (ie. PEP -275 and PEP-3103), want to introduce switch syntax to Python. However, there is no unanimous consensus on "whether and how to perform range testing".
Range test, also known as 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 delivery of the final product.
The official document’s explanation of “Why Python does not introduce switch” actually comes from the opinions of Guido van Rossum, the father of Python, in PEP-3103:
Source: www.python.org/dev/peps/pe…
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 during the PyCon 2007 keynote, and the results showed that this proposal did not have widespread support. Therefore, I declined it.
In short, PEP proposal has been proposed, and the syntax implementation has taken shape, but the core developers do not seem to have reached a consensus, which ultimately led to the abortion of the proposal.
3. What did PEP-275 and PEP-3103 say?
PEP-3103 was proposed in 2006, and PEP-275 was proposed in 2001. What they have in common is that they put forward some necessity to introduce switch statements and analyzed several alternatives. The selected implementation plans, however, ended up being rejected.
Source: www.python.org/dev/peps/pe…
那么,我们就先来回顾一下核心开发者们都做出了哪些讨论,看一看如果 Python 要实现 switch 结构,会是怎么样子的?(PS:PEP 里还涉及其它内容,本文只摘取与 switch 直接相关的部分)
PEP-275 提出的语法结构如下:
switch EXPR: case CONSTANT: SUITE case CONSTANT: SUITE ... else: SUITE复制代码
其中 else 分支是可选的,如果没有它,并且前面的分支都不满足的话,就什么也不做。另外 case 值 constant 支持不同类型,因为 expr 表达式的类型是动态的。
PEP-275 还提出让 switch 不支持掉落(fall-through)行为,即每个 case 分支相互独立而完整,不用像 C 语言那样需要写 break。
该 PEP 还列举了一些其它的 issue:
- 重用现有关键字,不引入“switch”和“case”
- 使用新的关键字,避免与 C 的 switch 概念混淆
- 支持单分支多值选择(例如:case 'a', 'b', 'c': ...)
- 还有建议支持范围取值判断(例如:case 10..14: ...)
除了首选方案,该 PEP 还记录了几种风格各异的语法方案:
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 记录下了不少重要的思路和问题,为 PEP-3103 的出现做了很好的铺垫。
那么,我们再来看看由 Guido 编写的 PEP-3103 说了些什么吧。
它首先认可了 PEP-275 中的两个基础设定,例如,实现“隐式的 break”,不让 case 分支出现 fall-through 这种转移控制权的情况(其它语言似乎都要求显式地写 break);else 分支是可选的,复用 else 关键字,而不用引入“default”。
对于 PEP-275 提倡的那种风格,Guido 比较认可,但也认为它的问题是缩进层次太多,因此建议减少代码分支缩进的空格数,例如本来缩进 4 空格,改为缩进 2 空格。
PEP-3103 还列举了另外三种实现方案,分析了它们的差异以及问题,具体内容从略,这里只给大家看看它们的风格:
# case 分支不缩进switch EXPR: case EXPR: SUITE case EXPR: SUITE ....else: SUITE# switch 语句后不加冒号switch EXPR case EXPR: SUITE case EXPR: SUITE ....else: SUITE# 省略 case 关键字switch EXPR: EXPR: SUITE EXPR: SUITE ... else: SUITE复制代码
在基础语法之外,Guido 花了很多篇幅来讨论扩展语法(Extended Syntax),即在一个 case 分支中实现匹配多个值的复杂情况:
case EXPR, EXPR, ...:# Guido 优选的case in EXPR_LIST: case *EXPR: case [*]EXPR, [*]EXPR, ...: case *(EXPR, EXPR, ...):复制代码
他重点考虑到的问题包括:switch 中表达式的结果是元组或可迭代对象的情况、case 的值被看成元组解包的情况、在 case 分支作“*”星号操作……
接着,Guido 又用了非常非常多的篇幅来分析该如何实现 switch,其中讨论到的主要思路有:
- 使用等价的 if-elif 链来定义 switch 语句(可能会做些优化)
- 同上,另外所有表达式都必须是可哈希的(hashable)
- 看作是预先计算的字典的分派(dispatch)
PEP 中这部分的内容非常多,因为在每个思路上,Guido 还考虑到了好几种实现路径,这导致了他在复杂分析后的结论是:It is too early to decide( 现在做决定为时尚早)。
阅读完 PEP-3103 后,我总体的感觉是:Guido 的思路非常发散、层次丰富,但是,缺少了他在面对其它问题时那“快刀斩乱麻”式的洞察力。
也就是说,在诸多的可能性方案中,他力求面面俱到,最终无法说服自己做出一个独裁的决定。阻力主要来自于他自己,而不是其他人。
不过,之所以会出现这种情况,也许跟他的预设立场有关:他似乎认为“Python is fine without a switch statement”,因此尽管写了很长的 PEP,但只是在把问题复杂化,把议题搁置起来。
最后,他在 PyCon 上做了一个小范围调查,借此“名正言顺”地拒绝了自己发起的 PEP,试图堵住众人的悠悠之口……
4、未来会有 switch 语句么?
归结起来,之所以 Python 没有 switch 语句,原因有:switch 的实现细节/功能点未经敲定、没有 switch 也挺好的、有其它不错的方法替代 switch、Guido 的小任性……
但是,我们还是要追问一句:未来会有 switch 语句么?或者类似的多分支选择结构?
为什么要有此一问呢?原因是有太多语言自带 switch 语句,而且也有很多人尝试编写提供 switch 功能的库(我记得在 PyCoder's Weekly 里曾见到过两次)。
我(Python猫)本人自始至终并不喜欢 switch,几乎可以肯定地说,Python 未来也不会有 switch,但是,它很可能会引入一个类似于 switch 且更为复杂的语法结构!
2020 年 6 月,PEP-622 被提出了,它建议引入在 Scala、Erlang 和 Rust 等语言中的模式匹配语法(pattern matching)。
截至 2020 年 10 月,该 PEP 已被分解成另外三个 PEP(634-636),目前都处于草案阶段。考虑到核心开发者们的参与情况以及话题讨论的情况,这些提案极有可能会在未来版本(比如正在开发中的 3.10)中实现。
以一个求平均数的函数为例,模式匹配语法可以实现成这样:
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)复制代码
match-case 结构神似于 switch-case 结构,然而它基于模式(pattern)而非表达式(expression),因此有更多待考虑的细节问题,也有更为广阔的应用空间。
对此话题感兴趣的读者,建议去查阅这几个新的 PEP。
最后,让我们回到标题中的问题:Python 为什么不支持 switch 语句?
官方文档的 FAQ 对此问题有一个解答,告诉我们有几个不错的替代写法,同时也留下了一条线索:曾有 PEP 提议引入 switch,只是没有成功实现。
沿着这条线索,本文拆解了 PEP-275 和 PEP-3103 这两篇文档,带大家看到了 Python 社区里提出过的风格各异的 switch 方案,以及诸多的悬而未决的问题。
最后,我们还关注到了最新的 PEP-622 的动态,看起来 switch 的“孪生兄弟” match 语法有望引入到 Python 中!switch 话题的讨论似乎要终止了,但是另一个更大的话题正在进行中!
相关免费学习推荐:python教程(视频)
The above is the detailed content of Why doesn't Python support switch statements?. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment