THE ZEN OF PYTHON
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!
Python-ideas邮箱用于向Python提出建议,有一些邮件很有意思。今天就来分享一个引发了许多Python开发者激烈讨论的问题。
while(tt–)
这个建议一看很有趣!
Currently in Python we have construction like this:
tt = 5
while t:
# do something
tt -= 1
It would be great if in Python we have something like this:
tt = 5
while (tt--):
# do something
It is exists in C++. And in my opinion it is very Pythonic
写正式邮件时千万不要这么写,没开头,没结尾,最后一句没句号……
分析一下:
这位Daniil同志觉得Python可以加入*变量- -*的写法。他认为这种写法非常Pythonic(大概指灵活性),但说实话我不这么觉得,因为这种写法非常容易出错(你在写tt--
时还得想一下是先-1再求值还是先求值再-1)。
对于这个提案,有人给出了回复。
翻译:
不知道你是不是在开玩笑,但你怎么不使用range
呢?不能再Pythonic了。
确实如此!用range不好吗?
这个人建议,你可以使用海象运算符,可以写得almost same!
随后又有一个人整活:
确实是almost!前一个人没有意识到所谓while (tt--)
是先求值再减,而tt:=tt-1
是先自减再求值!
用C语言举个例子:
#include<stdio.h>
int main(){
int i=0;
printf("%d",i++); //prints 0
}
#include<stdio.h>
int main(){
int i=0;
printf("%d",++i); //prints 1
}
你看,这么容易就出问题,这种语法怎么能被Python加上?即使很多语言都支持,Python未必就必须支持。正如这个人所说,Python is not going to be turned into C.
另一个人提出了更严峻的问题:
作为对C/C++的提醒:{前,后}-{增,减}量操作给这门语言带来了诸多问题,尤其是臭名昭著的未定义行为。如果你写过C或C++,光是看到这个表达式可能就会让你脊背发凉。
我不确定这些语法在Python中是否受欢迎。允许这样的语法感觉也不太符合Python的风格。
最糟糕的并不是求值顺序未定义,而是即便定义了,大多数人也不会记住规则,因为从语法上看并不直观。我甚至不确定大多数C程序员是否知道“序列点”是什么。
关于海象运算符的部分争议正是因为它使得求值顺序对理解程序更加重要。
a=a++
、(a++)+(++a)
的结果是什么?
f(a,a++,a)
中,传递的参数是多少?
前两个问题还好解决,但是第三个问题是最难解决的。不同的编译器可能导致不同结果。
我的看法
我也不支持Python加入自减自加的语法。事实上,Rust也不支持这种语法。这种语法会导致未定义行为,以至于出了bug你都不知道怎么回事。
在使用C/C++或JavaScript编程时,我也总是习惯使用++
或--
,但是我总是避免在f(a,a++,a)这种位置使用它。因此谨记谨慎使用自加/自减,这会引发很多bug。