>>9
Some operator should allow you to pass code as arguments. But let's suppose Python doesn't want to get into this. I'm fairly neutral to having this feature or not. At least, if, for, etc. should be expressions; not first-class data, but expressions that can appear in expression context. In fact, I don't see the need to differentiate "expression context" from "statement context".
Which differences between lambda and def are you talking about? Lambdas have limitations, but they're hardly arbitrary.
lambda and def essentially serve the same purpose (wasn't TOOWTDI a good thing?), yet they have different syntax which you have to learn, and you can't use these statements inside lambda, which is an arbitrary limitation coming from the arbitrary separation between some things that work like expressions, such as list comprehensions, and some things that do not, like if or for.
I'm not sure what and-or and if-else hacks you are referring to.
People wouldn't be doing dangerous and-or hacks (a and b or c works like C-like a ? b : c as long as b is true), or requesting the ?: conditional operator, which finally made it into Python but under an ugly syntax (b if a or c, WTF), if
if were an expression. They wouldn't have needed to use and-or that way, or to introduce if-else, if the language's comparison feature worked everywhere. The difference between the if statement and the if-else expression in Python 2.5 is like the difference between a hammer and a hammer for left-handed people.
How would you have things like if, def and lambda look?
I like the forced indentation of code. We don't have to give up on it. I'd propose that if, def, etc. become operators that work in expression context using a least-surprise syntax:
x = 1 + 2 + if a:
#Begin the forced indentation of code
y = 0
for i in xrange(...):
#Nested forced indentation of code
y = ...
y #This makes the "if" evaluate to y
#Now we can go back to the first indentation level, closing the if.
#As you would expect, an if without else returns None if false.
#And we could even define an else:
else:
c #Return c
So basically, this:
x = t if c else f
could be done as either:
x = if c:
t
else:
f
or also the more compact:
x = if c: t; else f
Everything would become expressions; semicolons or EOLs would be used as expression separators, and a block of code inside if, while, for or def should evaluate to the last expression evaluated inside.
As for lambda, I'd make it disappear and turn def into a better lambda. Example of previous usage:
fa = lambda x: x + 1
def fb(x):
while something:
...
return x + whatever
def _temp(x):
...statements...
return x + whatever
higher_order_function(1, 2, _temp, 3, 4)
My idea:
fa = def x: x + 1
#No need for parens
fb = def x:
while something:
...
x + whatever
#No need for _temp
higher_order_function(1, 2, def x:
...statements...
x + whatever
, 3, 4)
Of course, assignment statements should also become expressions. As in C.