[Python-Dev] Adding a conditional expression in Py3.0
rrr at ronadam.com
Thu Sep 29 18:21:18 CEST 2005
Antoine Pitrou wrote:
>>The only problem is that it's not easy to come up with a regex-based
>>way to transform
>> C and X or Y
>> X if C else Y
One way is to parse it manually to a list. This was just a test, but
more samples can be added friarly easy.
samples = [
# start, cond, x, y, end
("cgitb.py: file =", "file", "os.path.abspath(file)", "'?'", ""),
("cgitb.py: formatter =", '(self.format=="html")', "html", "text",
("compileal1.py: cfile = fullname + (", "__debug__","'c'","'o'",")"),
for s,c,x,y,e in samples:
print "%s %s and %s or %s %s" % (s,c,x,y,e)
print "%s %s if %s else %s %s" % (s,x,c,y,e)
print "%s (if %s then %s else %s) %s" % (s,c,x,y,e)
print "%s (%s ? %s : %s) %s" % (s,c,x,y,e)
> (my 2 cents)
> I find this proposal very confusing. The order is not logical at all.
> One usually expects to find the condition on one side, and the
> alternatives on another side (this is how it's done in every conditional
> construct I know of : traditional if-then-else, lisp's cond, switch
> statements...). But there the condition is in the middle, which breaks
> the natural reading order and feels obfuscated.
I found that my preference depends on the situation. I like (if cond
then expr1 else expr2) for most things because having the condition in
front tells me the purpose, And it's better represents the order the
terms are evaluated in.
But when checking a value and either changing it or leaving it alone, I
tended to want to type it as.
value = (value if cond else alternate_value)
In this case the condition is an accept or reject for the
alternate_value. And since the first term is a simple name instead of a
complex expression, the order of evaluation doesn't bother me.
Personally I prefer the function form best for the pure simplicity of
it, if(cond, e1, e2), but of course that doesn't do the shortcut
behavior and it pre-evaluates the arguments, so it's not an answer.
More information about the Python-Dev