Why Doesn't Python Have Switch/Case?
Why Doesn't Python Have Switch/Case?
Tuesday, June 09, 2015 (permalink)
Unlike every other programming language I've used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping:
def numbers_to_strings(argument): switcher = { 0: "zero", 1: "one", 2: "two", } return switcher.get(argument, "nothing")
This code is analogous to:
function(argument){ switch(argument) { case 0: return "zero"; case 1: return "one"; case 2: return "two"; default: return "nothing"; }; };
While the Python code is often more terse than the standard method of handling cases, I could argue it is more arcane. When I first started Python it felt weird and distracting. Over time it grew
on me, the use of a dictionary key being the identifier in a switch becoming more and more habitual.
Dictionary Mapping for Functions
In Python we can also include functions or lambdas in our dictionary mapping:
def zero(): return "zero" def one(): return "one" def numbers_to_functions_to_strings(argument): switcher = { 0: zero, 1: one, 2: lambda: "two", } # Get the function from switcher dictionary func = switcher.get(argument, lambda: "nothing") # Execute the function return func()
While the code inside zero() and one are simple, many Python programs use dictionary mappings like this to dispatch complex procedures.
Dispatch Methods for Classes
If we don't know what method to call on a class, we can use a dispatch method to determine it at runtime.
class Switcher(object): def numbers_to_methods_to_strings(self, argument): """Dispatch method""" # prefix the method_name with 'number_' because method names # cannot begin with an integer. method_name = 'number_' + str(argument) # Get the method from 'self'. Default to a lambda. method = getattr(self, method_name, lambda: "nothing") # Call the method as we return it return method() def number_0(self): return "zero" def number_1(self): return "one" def number_2(self): return "two"
Pretty nifty, right?
The Official Answer
The official answer says, "You
can do this easily enough with a sequence of if... elif... elif...else". And that you can use dictionary mapping for functions and dispatch methods
for classes.
Arguably the official answer doesn't explain anything except for workarounds. In other words, a "non-answer". In my opinion, what the official answer is really trying to say is, "Python doesn't need a case statement."
Really?
Yup. But there's more. I've heard people I respect say that switch/case statements in code can be really hard to debug.
Personally I find that argument breaks down as soon as you run into gigantic nested dictionaries used for mapping of code branches. Think about it, a 100+ element nested dictionary is just as hard to debug as a nested
switch and case block with 100+ cases.
Maybe Dictionary Mapping Runs Faster?
Moot as Python doesn't have a case statement. Talking about benchmarks from other languages is pointless as what is faster in one language is not always faster in another. Let's move on.
The Significant Advantage of Python's Approach
Every once in a while I walk into a scenario where Python's approach just works better than a switch/case statement. This is when at runtime I need to add or remove potential items from the mapping. When this occurs,
my years of practice of writing dictionary mappings and dispatch methods pays off. I have insights now that I never had back in the day when I relied on switch/case statements.
Closing Thoughts
To me, that Python forced me to accumulate lots of practical experience with mappings is a blessing in disguise. The constraint of not having switch/case statements allowed me to create approaches
and ideas I may not have developed with it.
Intentional or not, Python's lack of switch/case has been a social construct that made me a better coder.
Enough so that I think this accidental social construct is a better answer than the official one of 'Do this instead!'
The reference book I co-authored with Audrey Roy Greenfeld on Django best practices, Two
Scoops of Django 1.8, is now available in both print paperback and PDF formats.
原文转自:http://www.pydanny.com/why-doesnt-python-have-switch-case.html
Why Doesn't Python Have Switch/Case?的更多相关文章
- python中Switch/Case实现
学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现.所以不妨自己来实现Switch/Case功能. 方法一 通过字典实现 ...
- python技巧 switch case语句
不同于C语言和SHELL,python中没有switch case语句,关于为什么没有,官方的解释是这样的 使用Python模拟实现的方法: def switch_if(fun, x, y): ...
- Python | 基础系列 · Python为什么没有switch/case语句?
与我之前使用的所有语言都不同,Python没有switch/case语句.为了达到这种分支语句的效果,一般方法是使用字典映射: def numbers_to_strings(argument): sw ...
- Python里如何实现C中switch...case的功能
python没有switch case 不过可以通过建立字典实现类似的功能 例子:根据输入的年月日,判断是该年中的第几天 y = int(input('请输入年:')) m = int(input(' ...
- Android Studio快捷键switch case 轻松转换为if else
Android Studio快捷键switch case 轻松转换为if else 今天碰到的问题,没有找到资料,后面找到了方法,这个记下来,转载请注明出处:http://www.cnblogs.co ...
- java中的switch case
switch-case语句格式如下 switch(变量){ case 变量值1: //; break; case 变量值2: //...; break; ... case default: //... ...
- 为什么说在使用多条件判断时switch case语句比if语句效率高?
在学习JavaScript中的if控制语句和switch控制语句的时候,提到了使用多条件判断时switch case语句比if语句效率高,但是身为小白的我并没有在代码中看出有什么不同.去度娘找了半个小 ...
- c语言基础表达式, 关系运算符, 逻辑运算符, 位运算符, 数据的取值范围, 分支结构(if...else, switch...case)
1.表达式: 表达式的判断是有无结果(值), 最简单的表达式是一个常量或变量, 如:12, a, 3 + 1, a + b, a + 5 都是表达式 2.BOOL(布尔)数据类型: c语言中除了基本数 ...
- 运算符 与 分支语句:if ,else if,else;switch case
分支语句: if else if else : switch case --如何使用 if else if else: Console. ...
随机推荐
- Python求解啤酒问题(携程2016笔试题)
问题描述:一位酒商共有5桶葡萄酒和1桶啤酒,6个桶的容量分别为30升.32升.36升.38升.40升和62升,并且只卖整桶酒,不零卖.第一位顾客买走了2整桶葡萄酒,第二位顾客买走的葡萄酒是第一位顾客的 ...
- 前端性能监控系统 & 前端数据分析系统
前端监控系统 目前已经上线,欢迎使用! 背景:应工作要求,需要整理出前端项目的报错信息,尝试过很多统计工具,如: 腾讯bugly.听云.OneApm.还有一个忘记名字的工具. 因为各种原因,如: 统计 ...
- python AES加密解密 pycryptodome
环境 pyhton3.6 博主为了解码 AES 用了1天的时间,安了各种包,然而走了很多坑,在这里给大家提供一个简便的方法 首先在命令行(推荐) pip install Crypto 你会发现安装下 ...
- [SDOI 2015]约数个数和
Description 设d(x)为x的约数个数,给定N.M,求 $\sum^N_{i=1}\sum^M_{j=1}d(ij)$ Input 输入文件包含多组测试数据. 第一行,一个整数T,表示测试 ...
- BZOJ 4372 烁烁的游戏
Description 背景:烁烁很喜欢爬树,这吓坏了树上的皮皮鼠.题意:给定一颗n个节点的树,边权均为1,初始树上没有皮皮鼠.烁烁他每次会跳到一个节点u,把周围与他距离不超过d的节点各吸引出w只皮皮 ...
- [HNOI2006]公路修建问题
题目描述 输入输出格式 输入格式: 在实际评测时,将只会有m-1行公路 输出格式: 输入输出样例 输入样例#1: 复制 4 2 5 1 2 6 5 1 3 3 1 2 3 9 4 2 4 6 1 3 ...
- [Noi2016]区间
题目描述 在数轴上有 n个闭区间 [l1,r1],[l2,r2],...,[ln,rn].现在要从中选出 m 个区间,使得这 m个区间共同包含至少一个位置.换句话说,就是使得存在一个 x,使得对于每一 ...
- ●洛谷P3233 [HNOI2014]世界树
题链: https://www.luogu.org/problemnew/show/P3233题解: 虚树,dp,倍增. 首先对于每个询问,要把虚树建出来,这一步就从略了.这里着重分享一下如何求答案. ...
- ICM Technex 2017 and Codeforces Round #400 (Div. 1 + Div. 2, combined)
前四题比较水,E我看出是欧拉函数傻逼题,但我傻逼不会,百度了下开始学,最后在加时的时候A掉了 AC:ABCDE Rank:182 Rating:2193+34->2227 终于橙了,不知道能待几 ...
- mysql 使用问题?
linux中安装了mysql客户端和服务器端,为什么无法使用,总是报错呢 解决办法:使用dpkg -r mysql命令删除掉mysql-client和mysql-server了,还是不行,而且查看软件 ...