The entire reason lambda
exists is that it's an expression.1 If you want something that's like lambda
but is a statement, that's just def
.
Python expressions cannot contain statements. This is, in fact, fundamental to the language, and Python gets a lot of mileage out of that decision. It's the reason indentation for flow control works instead of being clunky as in many other attempts (like CoffeeScript). It's the reason you can read off the state changes by skimming the first object in each line. It's even part of the reason the language is easy to parse, both for the compiler and for human readers.2
改变Python以某种方式“逃避”语句-表达式鸿沟,除非以一种非常谨慎和有限的方式,否则会将其变成一种完全不同的语言,并且不再具有导致人们选择的许多好处首先是Python。
更改 Python 以生成大多数语句表达式(例如,Ruby)将再次将其变成完全不同的语言,而没有 Python 当前的优势。
And if Python did make either of those changes, then there'd no longer be a reason for lambda
in the first place;2,3 you could just use def
statements inside an expression.
改变Python来代替赋值表达式怎么样?嗯,很明显,这会破坏“您可以通过浏览每行中的第一个对象来读取状态变化”。尽管 Guido 通常关注的事实是if spam=eggs
是一个错误,而不是一个有用的东西。
事实上,Python 确实为您提供了在需要时解决这个问题的方法,例如setattr
甚至明确调用__setitem__
on globals()
,并不意味着它应该有直接的语法支持。很少需要的东西不值得语法糖,对于那些非常不寻常的东西更是如此,以至于在实际完成时应该引起人们的注意和/或危险信号。
1. I have no idea whether that was Guido's understanding when he originally added lambda
back in Python 1.0. But it's definitely the reason lambda
wasn't removed in Python 3.0.
2. In fact, Guido has, multiple times, suggested that allowing an LL(1) parser that humans can run in their heads is sufficient reason for the language being statement-based, to the point that other benefits don't even need to be discussed. I wrote about this a few years ago http://stupidpythonideas.blogspot.com/2015/01/statements-and-expressions.html if anyone's interested.
3. If you're wondering why so many languages do have a lambda
expression despite already having def
: In many languages, ranging from C++ to Ruby, function aren't first-class objects that can be passed around, so they had to invent a second thing that is first-class but works like a function. In others, from Smalltalk to Java, functions don't even exist, only methods, so again, they had to invent a second thing that's not a method but works like one. Python has neither of those problems.
4. A few languages, like C# and JavaScript, actually had perfectly working inline function definitions, but added some kind of lambda
syntax as pure syntactic sugar, to make it more concise and less boilerplatey. That might actually be worth doing in Python (although every attempt at a good syntax so far has fallen flat), but it wouldn't be the current lambda
syntax, which is nearly as verbose as def
.