Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: [Guido] Let me give you what you expect. If all the X if C else Y syntax does is prevent that atrocity from ever being introduced, it would be worth it. :) [Steve] Well, fine. However, it does allow atrocities like func(f for f in lst if f -1 if f 0 else +1) No it doesn't! Inside an 'if' (of any flavor), further ifs have to be nested. So you'd have to write func(f for f in lst if f (-1 if f 0 else +1)) or perhaps func(f for f in lst if (f -1 if f 0 else +1)) But I doubt you meant to write +1 where True could have sufficed. :) :) All that said, inside an if is hardly the best place for a conditional of any kind. Clearly such usage can go down as abuse. An if-else expression has lower priority than anything else except lambda; the expression lambda x: x if x = 0 else -x is equivalent to lambda x: (x if x = 0 else -x) That's about the only way it would make sense, I suppose. I realise that any chosen syntax is subject to abuse, but a conditional expression in a (currently allowed) conditional context will be guaranteed obscure. Your original instinct to omit conditional expressions was right! Now you've pushed me over the edge. I've made up my mind now, X if C else Y it will be. I hope to find time to implement it in Python 2.5. Let it be as controversial as bool or @decorator, I don't care. Not before time, either. If this ends the discussion then I'll consider I've done everyone a favour. Sometimes no decision is worse than the wrong decision ;-). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
I did this for my favorite proposal, and ended up with the list shown further down below. I think they all looks great! The fact that so few were found in whole of the standard library does put the use case into question, though, no? Though I am sure more could be found with a more thorough scan. There's lots of code in it that looks like this: def __init__(self, foo = None): if foo is not None: self.foo = foo else: self.foo = self.getFooDefault() With if/else it can be written: def __init__(self, foo = None): self.foo = foo if foo is not None else self.getFooDefault() However, I'm convinced that the latter version is less readable than the former. Often the line becomes more than 80 characters so there's no gain in translating it to an if-else expression because you would still have to split the line, other times the condition is so complex that it deserves its own line. Many opportunities for uses, but atleast as many for abuses. -- mvh Björn ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido: Now you've pushed me over the edge. I've made up my mind now, X if C else Y it will be. I hope to find time to implement it in Python 2.5. Steve Holden: Not before time, either. If this ends the discussion then I'll consider I've done everyone a favour. Sometimes no decision is worse than the wrong decision ;-). Exactly how I felt about bringing the decorator decision to a close. ;) Congratulations to you both! Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Wed, Sep 21, 2005, Nick Coghlan wrote: Steven Bethard wrote: Guido van Rossum wrote: I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. FWIW, I find this quite intuitive. It follows the same pattern as LCs and GEs -- remove the colons and add parentheses (or brackets for LCs). So I'm +1. *But*, in LC's and GE's, the body of the main clause of the statement is also pulled out and placed in front of the keyword: def gen(): for VAR in ITERABLE: if COND: yield EXPR becomes: gen = (EXPR for VAR in ITERABLE if COND) This makes sense to me, because the most important thing in the generator expression is the way each element is populated - the source iterable and the filtering condition do matter, but they aren't as important. Yes, and when the looping becomes the focal point, one should generally rewrite a listcomp as a for loop. Nevertheless, because boolean expressions have non-boolean semantics in Python (i.e. they return the objects rather than a boolean value), conditional expressions will almost certainly have the condition as the focal point because a simple boolean expression is no longer sufficient. I am therefore strongly opposed to the a if cond else b form. (We've already agreed that Raymond's proposal to make boolean expressions return booleans is dead, right?) I'm also opposed to elif in conditional expressions -- let's keep this a simple Pythonic rewrite of C's ternary. I'm +0 on requiring parentheses precisely because they're annoying. I'm still expecting simple boolean expressions to be the primary use case, and my hunch is that overall Python code will read better with the ternary looking cluttered. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
[Aahz] I'm also opposed to elif in conditional expressions -- let's keep this a simple Pythonic rewrite of C's ternary. I'm +0 on requiring parentheses precisely because they're annoying. I'm still expecting simple boolean expressions to be the primary use case, and my hunch is that overall Python code will read better with the ternary looking cluttered. FWIW, I scanned the standard library for all the and/or pairings where a conditional expression was applicable. This sampling can serve as a reference for what typical uses would look like in real Python code as created by a number of different authors. It only takes about five minutes to try out a given syntax proposal on all the fragments listed below. That short exercise provides an excellent insight into the look and feel of each proposal in real world code. Raymond - cgitb.py: file = file and os.path.abspath(file) or '?' cgitb.py: formatter = (self.format==html) and html or text compileal1.py: cfile = fullname + (__debug__ and 'c' or 'o') csv.py:(quotes[a] quotes[b]) and a or b, quotes.keys()) csv.py:(delims[a] delims[b]) and a or b, delims.keys()) csv.py: modes[char] = reduce(lambda a, b: a[1] b[1] and a or b, DocXMLRPCServer.py: anchor = (cl and cl.__name__ or '') + '-' + name fileinput.py:isfirstline() and * or , line) formatter.py: self.writer.send_paragraph((blankline and 1) or 0) gettext.py: __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext imaplib.py: l = map(lambda x:'%s: %s' % (x[0], x[1][0] and ' '.join(x[1]) or ''), l) imputil.py: _suffix_char = __debug__ and 'c' or 'o' keyword.py: iptfile = args and args[0] or Python/graminit.c pickle.py: self.write(obj and NEWTRUE or NEWFALSE) pickle.py: self.write(obj and TRUE or FALSE) pickletools.py: pos is None and unknown or pos, py_compile.py: cfile = file + (__debug__ and 'c' or 'o') pydoc.py: return result and re.sub('^ *\n', '', rstrip(result)) or '' pydoc.py: anchor = (cl and cl.__name__ or '') + '-' + name pydoc.py: lhs = name and 'strong%s/strong = ' % name or '' pydoc.py: contents = doc and [doc + '\n'] or [] pydoc.py: line = (name and name + ' = ' or '') + repr pydoc.py: line = (name and self.bold(name) + ' = ' or '') + repr pydoc.py: host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' pydoc.py: font = ('helvetica', sys.platform == 'win32' and 8 or 10) robotp~1.py: return (self.allowance and Allow or Disallow)+: +self.path telnet~1.py: cmd == DO and 'DO' or 'DONT', ord(opt)) telnet~1.py: cmd == WILL and 'WILL' or 'WONT', ord(opt)) thread~1.py:n!=1 and s or ) token.py: inFileName = args and args[0] or Include/token.h tokenize.py: yield (parenlev 0 and NL or NEWLINE, unittest.py: return doc and doc.split(\n)[0].strip() or None unittest.py: return doc and doc.split(\n)[0].strip() or None unittest.py: (run, run != 1 and s or , timeTaken)) urllib.py: safe_map[c] = (c in safe) and c or ('%%%02X' % i) urllib2.py: type = file and 'I' or 'D' xdrlib.py: print pred(x) and 'succeeded' or 'failed', ':', x xmlrpclib.py: write(value and 1 or 0) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/29/05, Raymond Hettinger [EMAIL PROTECTED] wrote: FWIW, I scanned the standard library for all the and/or pairings where a conditional expression was applicable. This sampling can serve as a reference for what typical uses would look like in real Python code as created by a number of different authors. It only takes about five minutes to try out a given syntax proposal on all the fragments listed below. That short exercise provides an excellent insight into the look and feel of each proposal in real world code. I did this for my favorite proposal, and ended up with the list shown further down below. I think they all looks great! The only problem is that it's not easy to come up with a regex-based way to transform C and X or Y into X if C else Y because it's hard to determine where C starts. So I recommend that people leave existing and/or code alone but start writing if/else expressions in new code only. After all there's nothing wrong with and/or. cgitb.py: file = os.path.abspath(file) if file else '?' cgitb.py: formatter = html if self.format == html else text compileal1.py: cfile = fullname + ('c' if __debug__ else 'o') csv.py:a if (quotes[a] quotes[b]) else b, quotes.keys()) csv.py:a if (delims[a] delims[b]) else b, delims.keys()) csv.py: modes[char] = reduce(lambda a, b: a if a[1] b[1] else b, DocXMLRPCServer.py: anchor = (cl.__name__ if cl else '') + '-' + name fileinput.py:* if isfirstline() else , line) formatter.py: self.writer.send_paragraph((1) if blankline else 0) gettext.py: __builtin__.__dict__['_'] = self.ugettext if unicode else self.gettext imaplib.py: l = map(lambda x:'%s: %s' % (x[0], ' '.join(x[1]) if x[1][0] else ''), l) imputil.py: _suffix_char = 'c' if __debug__ else 'o' keyword.py: iptfile = args[0] if args else Python/graminit.c pickle.py: self.write(NEWTRUE if obj else NEWFALSE) pickle.py: self.write(TRUE if obj else FALSE) pickletools.py: unknown if pos is None else pos, py_compile.py: cfile = file + ('c' if __debug__ else 'o') pydoc.py: return re.sub('^ *\n', '', rstrip(result)) if result else '' pydoc.py: anchor = (cl.__name__ if cl else '') + '-' + name pydoc.py: lhs = 'strong%s/strong = ' % name if name else '' pydoc.py: contents = [doc + '\n'] if doc else [] pydoc.py: line = (name + ' = ' if name else '') + repr pydoc.py: line = (self.bold(name) + ' = ' if name else '') + repr pydoc.py: host = '127.0.0.1' if (sys.platform == 'mac') else 'localhost' pydoc.py: font = ('helvetica', 8 if sys.platform == 'win32' else 10) robotp~1.py: return (self.Allow if allowance else Disallow)+: +self.path telnet~1.py: 'DO' if cmd == DO else 'DONT', ord(opt)) telnet~1.py: 'WILL' if cmd == WILL else 'WONT', ord(opt)) thread~1.py:s if n!=1 else ) token.py: inFileName = args[0] if args else Include/token.h tokenize.py: yield (parenlev NL if 0 else NEWLINE, unittest.py: return doc.split(\n)[0].strip() if doc else None unittest.py: return doc.split(\n)[0].strip() if doc else None unittest.py: (run, run != s if 1 else , timeTaken)) urllib.py: safe_map[c] = c if (c in safe) else ('%%%02X' % i) urllib2.py: type = 'I' if file else 'D' xdrlib.py: print 'succeed' if pred(x) else 'failed', ':', x xmlrpclib.py: write(1 if value else 0) -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/29/05, Guido van Rossum [EMAIL PROTECTED] wrote: [a garbled list] Stupid gmail broke the lines. Here it is again as an attachment. -- --Guido van Rossum (home page: http://www.python.org/~guido/) XifCelseY.py Description: application/python ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: I think they all looks great! expression if expression? looks like you've been doing too much Perl hacking lately ;-) /F ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
The only problem is that it's not easy to come up with a regex-based way to transform C and X or Y into X if C else Y (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. This is especially true if the X in X if C else Y happens to be a non-trivial expression - witness your example from unittest.py: return doc.split(\n)[0].strip() if doc else None ... because then the condition (which is the most important part of the statement) is shadowed by the complexity of the first alternative; and the two alternatives, which should logically be siblings, are separated by something which has a different role in the construct. This is exactly like a switch/case statement where the switch would have to be inserted in the middle of two case's. Also, generally, one of the most annoying things in computer languages is when they try to invent their own unnatural conditional forms: such as Perl's inverted forms or unless statement. Regards Antoine. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido After all there's nothing wrong with and/or. Especially if it's correct. wink Skip ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Raymond Hettinger wrote: [Aahz] I'm also opposed to elif in conditional expressions -- let's keep this a simple Pythonic rewrite of C's ternary. I'm +0 on requiring parentheses precisely because they're annoying. I'm still expecting simple boolean expressions to be the primary use case, and my hunch is that overall Python code will read better with the ternary looking cluttered. FWIW, I scanned the standard library for all the and/or pairings where a conditional expression was applicable. This sampling can serve as a reference for what typical uses would look like in real Python code as created by a number of different authors. Thanks for digging those out - I was thinking that would be a useful exercise, but hadn't taken the time to think of an easy way to find relevant lines. It only takes about five minutes to try out a given syntax proposal on all the fragments listed below. That short exercise provides an excellent insight into the look and feel of each proposal in real world code. I tried it with (if C then A else B) and (A if C else B), and found both to be significantly more readable than the current code. In particular, I wouldn't want to bet money that none of the examples are buggy, as there were a few cases where the A value could conceivably be 0 or '', but I couldn't tell if it was possible for the condition to also be true in those cases. Comparing the two syntaxes I tried, I found that the infix notation generally required the addition of parentheses around the A expression when that expression was itself a binary operation - otherwise the precedence was unclear and, even with parentheses around the whole conditional, the layout gave the impression that the conditional expression only applied to the second argument to the binary operation in A. That said, the more verbose form still felt like it had the elements out of sequence - it was just crying out for the expression to be rewritten as a statement. Regards, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.blogspot.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Antoine Pitrou wrote: This is especially true if the X in X if C else Y happens to be a non-trivial expression - witness your example from unittest.py: return doc.split(\n)[0].strip() if doc else None ... because then the condition (which is the most important part of the statement) is shadowed by the complexity of the first alternative; and the two alternatives, which should logically be siblings, are separated by something which has a different role in the construct. I think the perception of what's important is relevant here - to me, the behaviour in the normal case (i.e., non-empty doc) is the most important element. The conditional, and the default value returned when 'doc' is empty are interesting, but are a corner case, rather than a fundamental element of the function's behaviour. This is exactly like a switch/case statement where the switch would have to be inserted in the middle of two case's. Well, no - because it is possible to consider an if-else as a parameterised binary operation that chooses between the left and right operands (i.e., it's like an or, only we're asking that the decision be made based on something other than the truth value of the left hand operand). That is, in the case where the left hand expression has no side effects, the following pairs of expression are essentially equivalent: a or b - a if a else b a and b - a if not a else b In the switch statement example, the switch statement is inherently an n-ary operation, so there is no comparable way of finding a spot to put the switch variable in the middle. Also, generally, one of the most annoying things in computer languages is when they try to invent their own unnatural conditional forms: such as Perl's inverted forms or unless statement. Even more annoying are constructs that don't gel with the rest of the language, though. Regards, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.blogspot.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: file = os.path.abspath(file) if file else '?' ... These are all unreadable. In C a ? b : c is not used very often. A quick check of the Python source found 476 occurences. -1 to conditional expressions. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: On 9/29/05, Raymond Hettinger [EMAIL PROTECTED] wrote: FWIW, I scanned the standard library for all the and/or pairings where a conditional expression was applicable. This sampling can serve as a reference for what typical uses would look like in real Python code as created by a number of different authors. It only takes about five minutes to try out a given syntax proposal on all the fragments listed below. That short exercise provides an excellent insight into the look and feel of each proposal in real world code. I did this for my favorite proposal, and ended up with the list shown further down below. I think they all looks great! The fact that so few were found in whole of the standard library does put the use case into question, though, no? Though I am sure more could be found with a more thorough scan. The only problem is that it's not easy to come up with a regex-based way to transform C and X or Y into X if C else Y because it's hard to determine where C starts. So I recommend that people leave existing and/or code alone but start writing if/else expressions in new code only. After all there's nothing wrong with and/or. cgitb.py: file = os.path.abspath(file) if file else '?' cgitb.py: formatter = html if self.format == html else text compileal1.py: cfile = fullname + ('c' if __debug__ else 'o') csv.py:a if (quotes[a] quotes[b]) else b, quotes.keys()) csv.py:a if (delims[a] delims[b]) else b, delims.keys()) csv.py: modes[char] = reduce(lambda a, b: a if a[1] b[1] else b, DocXMLRPCServer.py: anchor = (cl.__name__ if cl else '') + '-' + name fileinput.py:* if isfirstline() else , line) formatter.py: self.writer.send_paragraph((1) if blankline else 0) gettext.py: __builtin__.__dict__['_'] = self.ugettext if unicode else self.gettext imaplib.py: l = map(lambda x:'%s: %s' % (x[0], ' '.join(x[1]) if x[1][0] else ''), l) imputil.py: _suffix_char = 'c' if __debug__ else 'o' keyword.py: iptfile = args[0] if args else Python/graminit.c pickle.py: self.write(NEWTRUE if obj else NEWFALSE) pickle.py: self.write(TRUE if obj else FALSE) pickletools.py: unknown if pos is None else pos, py_compile.py: cfile = file + ('c' if __debug__ else 'o') pydoc.py: return re.sub('^ *\n', '', rstrip(result)) if result else '' pydoc.py: anchor = (cl.__name__ if cl else '') + '-' + name pydoc.py: lhs = 'strong%s/strong = ' % name if name else '' pydoc.py: contents = [doc + '\n'] if doc else [] pydoc.py: line = (name + ' = ' if name else '') + repr pydoc.py: line = (self.bold(name) + ' = ' if name else '') + repr pydoc.py: host = '127.0.0.1' if (sys.platform == 'mac') else 'localhost' pydoc.py: font = ('helvetica', 8 if sys.platform == 'win32' else 10) robotp~1.py: return (self.Allow if allowance else Disallow)+: +self.path telnet~1.py: 'DO' if cmd == DO else 'DONT', ord(opt)) telnet~1.py: 'WILL' if cmd == WILL else 'WONT', ord(opt)) thread~1.py:s if n!=1 else ) token.py: inFileName = args[0] if args else Include/token.h tokenize.py: yield (parenlev NL if 0 else NEWLINE, unittest.py: return doc.split(\n)[0].strip() if doc else None unittest.py: return doc.split(\n)[0].strip() if doc else None unittest.py: (run, run != s if 1 else , timeTaken)) urllib.py: safe_map[c] = c if (c in safe) else ('%%%02X' % i) urllib2.py: type = 'I' if file else 'D' xdrlib.py: print 'succeed' if pred(x) else 'failed', ':', x xmlrpclib.py: write(1 if value else 0) Having though about it more closely, the reason I believe it might confuse newbies is because until the else comes along the construct can easily be read as a statement with a conditional suffix, and it's only after you read the else it becomes obvious that it's the expression that's conditional. I realise that this reading will become habitual once this proposal is put into the language, but I do think this will be a source of confusion to newcomers (who should anyway be steered away from all the magic of ternary expressions, list comprehensions, generator expressions and the like. I would argue for mandatory parentheses around the expression, leaving room later (probably after Guido is no longer around to be sick at the site of it) for: def f(condition): return something if condition # no else! return somethingElse not-expecting-this-to-fly-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden
Re: [Python-Dev] Adding a conditional expression in Py3.0
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 into 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) print (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. Cheers, Ron ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/29/05, Steve Holden [EMAIL PROTECTED] wrote: I would argue for mandatory parentheses around the expression, leaving room later (probably after Guido is no longer around to be sick at the site of it) for: def f(condition): return something if condition # no else! return somethingElse not-expecting-this-to-fly-ly y'rs - steve Let me give you what you expect. If all the X if C else Y syntax does is prevent that atrocity from ever being introduced, it would be worth it. :) -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: I did this for my favorite proposal, and ended up with the list shown further down below. I think they all looks great! I'm sorry for my bad English IMHO, if condition is nontrivial, then the syntax: expr1 if some complex condition else expr2 can be more hard to read as compared with: if some complex condition then expr1 else expr2 In the second form visual comparison of expr1 and expr2 is simpler because its adjacent placement. For example, in expression 'DO' if cmd == DO and flag == OK or x is None else 'DONT' 'DO' and 'DONT' visually divided and eyes must move there and back for find the difference between them. As opposite, in expression if cmd == DO and flag == OK or x is None then 'DO' else 'DONT' it is very easy to determine what is possible expression output. It is a bit more readable from my point of view Best regards, Alexandermailto:[EMAIL PROTECTED] ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
[ongoing discussion of conditional expressions] I waited until I had caught up on my reading before saying anything. Now I'll express my opinion in a single posting then keep quiet unless I actually find I have something novel to contribute (difficult in a topic that's been talked to death 3 or 4 times in the past few years). * I am STRONGLY in favor of introducing a conditional expression in some form. The use of the and-or trick is proof enough to me that there is a need for it. I can marshall other arguments also, but they appear unnecessary. * The syntax to use is a place where we need a BDFL decision. Make the decision and we'll all agree and move on. Any decision would be better than an eternity of re-discovering old ideas again and again. * I think the two best options are trueval if cond else falseval and if cond then trueval else falseval The first has brevity in it's favor, and cleverness which might be an advantage or disadvantage depending on your point of view. The second has order-of-arguments in its favor. In either case, wise programmers will use parenthesees when it aids clarity (imagine v1 if c else v2 + v3). Whether we require parenthesees when the parser could disambiguate on its own is really up to Guido. * I prefer the second form (if cond then trueval else falseval) because it puzzles _nobody_ at the expense of being slightly more wordy and less clever. But that's just one person's opinion. Thanks Guido, for maintaining your patience in the face of this discussion. -- Michael Chermside ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] After all there's nothing wrong with and/or. This is one reason 'no addition' got a relatively high rank in the vote. Examples... telnet~1.py:'DO' if cmd == DO else 'DONT', versuscmd == DO and 'DO' or 'DONT' I still stronly prefer this order and even slightly prefer this form. I might even prefer a complete inversion of the order: x else y if c 'DO' else 'DONT' if cmd != DO except that that does not chain at all well. Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: On 9/29/05, Steve Holden [EMAIL PROTECTED] wrote: I would argue for mandatory parentheses around the expression, leaving room later (probably after Guido is no longer around to be sick at the site of it) for: def f(condition): return something if condition # no else! return somethingElse not-expecting-this-to-fly-ly y'rs - steve Let me give you what you expect. If all the X if C else Y syntax does is prevent that atrocity from ever being introduced, it would be worth it. :) Well, fine. However, it does allow atrocities like func(f for f in lst if f -1 if f 0 else +1) I realise that any chosen syntax is subject to abuse, but a conditional expression in a (currently allowed) conditional context will be guaranteed obscure. Your original instinct to omit conditional expressions was right! far-too-late-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
[Guido] Let me give you what you expect. If all the X if C else Y syntax does is prevent that atrocity from ever being introduced, it would be worth it. :) [Steve] Well, fine. However, it does allow atrocities like func(f for f in lst if f -1 if f 0 else +1) No it doesn't! Inside an 'if' (of any flavor), further ifs have to be nested. So you'd have to write func(f for f in lst if f (-1 if f 0 else +1)) or perhaps func(f for f in lst if (f -1 if f 0 else +1)) But I doubt you meant to write +1 where True could have sufficed. :) An if-else expression has lower priority than anything else except lambda; the expression lambda x: x if x = 0 else -x is equivalent to lambda x: (x if x = 0 else -x) I realise that any chosen syntax is subject to abuse, but a conditional expression in a (currently allowed) conditional context will be guaranteed obscure. Your original instinct to omit conditional expressions was right! Now you've pushed me over the edge. I've made up my mind now, X if C else Y it will be. I hope to find time to implement it in Python 2.5. Let it be as controversial as bool or @decorator, I don't care. -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Nick Coghlan wrote: i.e., it's like an or, only we're asking that the decision be made based on something other than the truth value of the left hand operand. Hmmm, then maybe it should be a or c if b or perhaps a or, if b, c :-) -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Gustavo J. A. M. Carneiro wrote: More realistic example: def greet(person=None): print Hello %s % (if person is None: World else: person) Not as compact as C's ?:, but more readable and intuitive. It's just like an if-else construct, but on a single line and () around to make it look like an expression instead of a statement. It looks even more like an expression without any embedded colons ;) def greet(person=None): # Infix conditional print Hello %s % (World if person is None else person) def greet(person=None): # Negated infix conditional so that 'normal' value is first print Hello %s % (person if person is not None else World) def greet(person=None): # Prefix conditional print Hello %s % (if person is None then World else person) Anyway, Guido's already given some indication that the PEP 308 infix and prefix conditional operators without colons (above) are the main options he is considering choosing from. Regards, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.blogspot.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Saturday 2005-09-24 04:21, Terry Reedy wrote: Never wrote a single line, and may have not read one (in DDJ? Byte?) for 15-20 years. How do *you* read such C? Cond 'Qmark' ? I seldom have to read C code aloud, and the ?: operator is rare-ish; but I would suggest reading a?b:c as a chooses b else c or (shaving a syllable) a gives b else c or something like that. Or, ploddingly but unambiguously, a query b colon c. Now, can you honestly say that you would (naively) read return foo if bar else baz and be certain you knew what it meant? I can't imagine *actually* reading it as if foo were the condition. But I can imagine reading it, to begin with, as if it were a Perlish conditionalized statement: (return foo) if bar else ... aw heck, that can't be right. Which is probably benign but slows down comprehension. -- g ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Sokolov Yura wrote: Sorry for looking in every hole. Just a suggestion. A= condition and first or second problem is in case when first in (None,0,[],). May be invent new operator 'take'. take - returns right operator when left evals to True and stops computing condidtional expression. Then we could write: A = condition take first or second. A = x==y take w or s A = z is not None and q!=12 take [] or allowable(z,q) take [(z,q)] or Impossible Ok, it might looks ugly. But may be not. One of the advantages of (if x then y else z) is that it doesn't require the introduction of a new keyword (I think the then could be special- cased like as in the import statement). Reinhold -- Mail address is perfectly valid! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Terry Reedy wrote: Now, can you honestly say that you would (naively) read return foo if bar else baz and be certain you knew what it meant? I can honestly say that, given I knew I was reading Python code, it would never have entered by head to read foo if as meaning that foo was the condition. Bizarrely backwards too much it would be. Greg ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/24/05, Terry Reedy [EMAIL PROTECTED] wrote: Now, can you honestly say that you would (naively) read return foo if bar else baz and be certain you knew what it meant? FWIW, yes, I can honestly say that I would be certain. Yes, you may be able to *parse* it as (foo if) bar (esle baz) as well as foo (if bar) (else baz), but I know of no conceivable *semantic* meaning for foo if - English has no postfix if, and nor do any programming languages, except entirely postfix ones such as Forth. Paul. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
The reason I like a if b else c is because it has the most natural word order. In English, My dog is happy if he has a bone, else sad. sounds much more natural than My dog is, if he has a bone, happy, else sad. Neither sounds very natural to me; conditional expressions don't occur much in English. It's much more common to hear something like My dog is happy if he has a bone; otherwise he's sad. And that would correspond to a postfix conditional operator on *statements*, not expressions; Perl and Ruby have this, but it doesn't seem very Pythonic. Interestingly, it looks *more* odd to me if parens are included: return (self.arg if self.arg is not None else default) I think this is because, without the parens, I tend to read the if as applying to the whole phrase return self.arg, not just to the self.arg. Which is one reason why I *don't* like the proposed consequent if antecedent else alternative syntax; it looks like a statement modifier when it isn't really one. When you're forced (by the parens) to read it correctly, you stop liking it! :-) * Conditional expressions do occur in English, though, and they do generally have the consequent at the front. But ... they also generally have the else-marker right at the end. Buy some pork if it's going cheap, and some beef if not. You can divide an angle into N equal parts with ruler and compasses if N is a power of 2 times a product of distinct Fermat primes, but not if N has any other form. I sleep all night and work all day. I don't think a syntax that authentically mirrors the structure of conditional expressions in English is likely to be very good. x = (123 if p==q; 321 otherwise) x = (123 if p==q, else 321 if not) x = (123 if p==q; else 321 if r==s; else 999 if not) :-) -- g ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/20/05, Nick Coghlan [EMAIL PROTECTED] wrote: Basically, I'm +1 on the original PEP 308 form because it reads more naturally (and more like LC's and GE's) to me in expression contexts, and +0 on the if/then/elif/else form (because I would like a real conditional operator). I agree that (expr if cond else expr) fits far more naturally these days given the ordering of generator expressions (and list comprehensions, but they were around when PEP 308 was discussed, so I don't think they work as well as evidence :-)) Also, (expr if cond else expr) doesn't naturally admit an elif case, reducing complexity (and the tendency to overuse the construct in complex ways) a little. And it doesn't need a new keyword. I have a vague fondness for this form. I really can't express it very well, but the if-then-else version just feels a little too boring and conventional. I'm sure people will get used to it (heck, we've got decorators and print :-)) but maybe pushing a (mildly) idiosyncratic form isn't worth opening that can of worms again. I'm +1 on a conditiona expression. I suspect the time is now right. I'm +1 on *one* of (expr if cond else expr) or (if cond then expr else expr) With the latter, I don't mind if elif is added or not. I'm +10 on Guido just making the decision. No more votes, please! Paul. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Gareth McCaughan [EMAIL PROTECTED] wrote: [seems to have gone off list with a portion of the discussion] The reason I like a if b else c is because it has the most natural word order. In English, My dog is happy if he has a bone, else sad. sounds much more natural than My dog is, if he has a bone, happy, else sad. Neither sounds very natural to me; conditional expressions don't occur much in English. It's much more common to hear something like My dog is happy if he has a bone; otherwise he's sad. Natural english wise, this also sounds natural: If my dog has a bone he's happy, otherwise he's sad. But yeah, I'll use them regardless of the syntax, even if I have preferences. - Josiah ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Need I continue? Or is the dead still dead? Since 'a if b else c' is not obviously dead, I will summarize my argument against it thusly: It is ambiguous to people because it is can be parsed (by people, who are not automatons) as either '(a if) b (else c)' or 'a (if b) (else c)'. The first parsing, seeing a as the conditional rather than the consequent, as in the the second, is at least as reasonable as the second given precedents in both other algorithm languages and natural languages (in English, at least, but I suspect others also). Ambiguity sometimes leads to discomfort. As important, it sometimes leads to bugs either in writing or reading. The impetus for this discussion was a real-life buggy example of the and/or construct. Its replacement should be something not similarly bug-prone, even if for a different reason. Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Jim Jewett [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] A nice summary, to which I will add just a little. For a conditional expression, I think the choices are really down to the following, which was already way too much freedom last (http://www.python.org/peps/pep-0308.html) time: (1) Should it be done at all? + It would be useful, and avoid certain types of bugs. - It would encourage bracketing instead of indentation PEP 308 decided not yet, anyhow (2) How many of the keywords (if ... then ... else ... elif) should be dropped? (if test then True else False) + standard english + standard programming idiom - adds a then keyword (if test True else False) + better parallels the if: statement - starts to run together I think the first form with 'then' better parallels the 'if cond :' statement because 'then' functions as a separator between test and True just as ':' or ':\n' functions as a separator between cond and True body. (if test1 Val1 elif test2 Val2 elif test3 Val3) + parallels the if: statement - encourages overly long code * but still better than nested parens PEP 308 wasn't entirely clear; the words said to keep elif, but the examples did not. There was some disagreement on which of the other three keywords to represent explicitly. (Rather than only by position.) (3) What order should the clauses appear? (if test then True else False) (if test1 then Val1 elif test2 Val2 elif test3 Val3 else Val4) + Natural Order - do we need then? (True if normal else False) (Val1 if test1 else Val2 if test2 else Val3 if test3 else Val4) + Best order for normal/default conditionals + Best order in general if we weren't used to left-right processing I an far from convinced on either of these, perhaps because I am not sure about the actual claim. - But we *do* expect left-right almost everywhere except assignments - Ambiguous. When expressions a and b both lack boolean operators, as is common in Python given that all objects have a boolean value, a if b else c is mentally parseable as either (a if) b (else c) or a (if b) (else c). I initially though the proposal intended the first. -- Bug prone. The left-right expectation leads to the wrong parsing. Hence we may expect occasional bugs both in writing and reading this construct. PEP 308 made it clear that else should be last. Putting the condition before the then was not as clearcut. (4) What sort of punctuation should augment or replace the keywords? PEP 308 suggested avoiding punctuation, but it wasn't clearcut. Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Greg Ewing [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Terry Reedy wrote: Many people, perhaps most, including me, read exp1 if exp2 else exp3 # as cond if etrue else efalse # in direct analogy with cond ? etrue : efalse # from C I'd have thought only Forth programmers would be prone to that! Never wrote a single line, and may have not read one (in DDJ? Byte?) for 15-20 years. How do *you* read such C? Cond 'Qmark' ? It would surprise me greatly if it's really true that *most* people would read it that way. OK. I withdraw 'possibly most' as not directly relevant. It would not take that many people to have enough people mistakenly write or read it that way for this construct to be somewhat as bug prone, in practice, as and/or. During the c.l.p debate, someone counted about 100 correct uses of 'a and b or c' in the standard library. But one real misuse edged Guido toward replacing it. So I think the replacement should be as clear as reasonably possible and clearly an improvement. Especially given that, in real code, you're not going to be looking at abstract names like exp1, exp2, exp3, but (hopefully) something a lot more meaningful. Because every object in *Python* (ignoring buggy or unusual __nonzero__ methods) has a boolean value, any expression can be a conditional expression and hence conditional expressions often lack a boolean operator to flag the expression as the likely conditional. Can you honestly say that you would read Given that setup, how could I possible misread :-? return red_value if color == 'red' else blue_value as if red_value: return color == 'red' else: return blue_value ? I can imagine that if I were to read the return naively, I might wonder whether the expressions were reversed. And certainly, not all code I have read has had such obvious names. Now, can you honestly say that you would (naively) read return foo if bar else baz and be certain you knew what it meant? Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Terry Reedy wrote: During the c.l.p debate, someone counted about 100 correct uses of 'a and b or c' in the standard library. But one real misuse edged Guido toward replacing it. So I think the replacement should be as clear as reasonably possible and clearly an improvement. But I think there's a difference in kind here - to *fix* Raymond's example required a fundamental change to the structure of the line, none of which looked as clean as the original. There is no way to get the and/or construct to gracefully handle the case where the desired result in the 'true' case might itself be false: either you change to using an if statement, or you use a workaround like the ugly singleton-list approach. That is, the following is fundamentally broken for pure imaginary numbers: return isinstance(z, ComplexType) and z.real or z Fixing it requires changing to either: return (isinstance(z, ComplexType) and [z.real] or [z])[0] or: if isinstance(z, ComplexType) return z.real else: return z This is not the case with an in-fix notation for conditional expressions - you can fix a broken line simply by moving the relevant expressions to the correct locations. return isinstance(z, ComplexType) if z.real else z # Broken! return z.real if isinstance(z, ComplexType) else z # Correct! I see this as being in the same category of error as writing return foo ** baz when you really should have written return baz ** foo (i.e., not the language's problem). (Random aside: it would be nice if foo ** bar % baz automatically invoked the three argument form of 'pow') Now, can you honestly say that you would (naively) read return foo if bar else baz and be certain you knew what it meant? Yes. I'd expect it to read like English - Return foo if bar is true, otherwise return baz. Whether that was was what code was *supposed* to be doing, I couldn't assess without additional context (but that is true regardless of the syntax). With the prefix notation used for C's conditional operator, I simply don't read it in the order it's written - I read return bar ? foo : baz as if bar is true then return foo, otherwise return baz. That's possible with C because it uses punctuation - using an English keyword instead makes it significantly harder for me to consider interpreting the construct that way (In fact, the only way I can get my brain to accept it is by mentally replacing the if with ? and the else with :). Does it help if you think of if C else as a parameterised infix operation for choosing between the expressions on either side? Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.blogspot.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/23/05, Nick Coghlan [EMAIL PROTECTED] wrote: But I think there's a difference in kind here - to *fix* Raymond's example required a fundamental change to the structure of the line, none of which looked as clean as the original. There is no way to get the and/or construct to gracefully handle the case where the desired result in the 'true' case might itself be false: either you change to using an if statement, or you use a workaround like the ugly singleton-list approach. That is, the following is fundamentally broken for pure imaginary numbers: return isinstance(z, ComplexType) and z.real or z It's hard to say whether this fixes Raymond's example when the goal wasn't clearly stated, but I find a non ternary option lambda z: complex(z).real more readable than any of the variants proposed so far. The obvious downsides are that it can raise a ValueError, and turns integers into floats. But if the input list is all numeric, it has clean results. -- Michael Urman ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Nick Coghlan [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] snip discussion indicating that our brains work different on this issue I am reminded of how some people seem to react to fingernails on a blackboard, while the screech is just another noise to me, except that I am in the opposite position with respect to a if b else c. Does it help if you think of if C else as a parameterised infix operation for choosing between the expressions on either side? Hmm. If I parse it as a (if b else) c and sort of ignore the words and think of it as T c F so that the whole thing is a switch pointing either left or right? A bit strange, but perhaps it does. Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Andrew Koenig [EMAIL PROTECTED] wrote: My problem with this syntax is that it can be hard to read: return if self.arg is None then default else self.arg looks worryingly like return NAME NAME.NAME NAME NAME NAME NAME NAME NAME.NAME to me. Interesting. What about return if self.arg is None: default else: self.arg That's awful. It would confuse everyone as to why LCs and GEs don't have punctuation while these do. In that sense, I am not convinced that it should have keywords AND punctuation, one or the other. - Josiah ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Jason Orendorff wrote: Honestly, I think I would prefer this syntax. Examples from real code, before and after: lines = [line for line in pr.block.body if line.logical_line.strip() != ''] lines = [for line in pr.block.body: if line.logical_line.strip() != '': line] row.values = \ [line[col.start:col.end].strip() for col in columns] row.values = \ [for col in columns: line[col.start:col.end].rstrip()] return [p for p in self.listdir(pattern) if p.isdir()] return [for p in self.listdir(pattern): if p.isdir(): p] -1. Too much similarity with the for/if statement. People would say why can we put a for statement in brackets but not a try statement. Reinhold -- Mail address is perfectly valid! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. FWLIW, this was my (strong) preference back at the time of the original discussion. -- g ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum [EMAIL PROTECTED] writes: Given the later addition of generator expressions with mandatory parentheses , the mandatory-parentheses version of a conditional expression looks less strange to me than it did then ;-). So I could happily use it even though I may still lean toward the other option 2 version (then-else) due to its not needing ':'s or a third elseif term for chaining. I think I'd prefer (if expr then expr else expre) i.e. no colons. My problem with this syntax is that it can be hard to read: return if self.arg is None then default else self.arg looks worryingly like return NAME NAME.NAME NAME NAME NAME NAME NAME NAME.NAME to me. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. This is also true. *If* you want general community input, I would suggest a runoff ballot with those four choices (and a summary of pros and cons of each), or fewer if you see any as unacceptible. If there's one thing I've learned from the PEP 308 vote, it is that votes for language don't work. I prefer some discussion on Python-dev after which I pick one. Well, this is my input (and now I'm going to try and stay out of it). Cheers, mwh -- 59. In English every word can be verbed. Would that it were so in our programming languages. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Wed, 2005-09-21 at 11:10, Michael Hudson wrote: My problem with this syntax is that it can be hard to read: return if self.arg is None then default else self.arg looks worryingly like return NAME NAME.NAME NAME NAME NAME NAME NAME NAME.NAME to me. I think that requriing parens helps a lot with the list-of-names problem - it nicely delimits the conditional expression for human readers: return (if self.arg is None then default else self.arg) In particular it breaks up the misleading grouping return if. Mark Russell ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Greg Ewing wrote: Guido van Rossum wrote: I think if we go with (if ... then ... else ...) or (if ...: ... else: ...) we'll have to support elif as well: (if ... then ... elif ... then ... else ...) or (if ...: ... elif ...: ... else: ...) One nice thing about x if b else y is that it chains without needing any more keywords: x if b else y if c else z But if you require parens, it's not so nice: (x if b else (y if c else z)) If Guido chose this form, I would expect the chaining to work like chaining loops in a generator expression, with parentheses being required around the whole thing, rather than around each element in the chain: (x if b else y if c else z) The point being that the result of the conditional expression is exactly one of the options included in the expression, so only one set of parentheses is required. Regards, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.blogspot.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Nick Coghlan wrote: Greg Ewing wrote: One nice thing about x if b else y is that it chains without needing any more keywords: x if b else y if c else z But if you require parens, it's not so nice: (x if b else (y if c else z)) If Guido chose this form, I would expect the chaining to work like chaining loops in a generator expression, with parentheses being required around the whole thing, rather than around each element in the chain: (x if b else y if c else z) The point being that the result of the conditional expression is exactly one of the options included in the expression, so only one set of parentheses is required. Either a or b could be a nested expression so it's important that it be readable in both cases. (a if e then b) ((a1 if e1 then b1) if e then b) (a if e then (a2 if e2 then b2)) ((a1 if e1 then b1) if e then (a2 if e2 then b2)) Without parentheses... (a if e then b) (a1 if e1 then b1 if e then b) (a if e then a2 if e2 then b2) (a1 if e1 then b1 if e then a2 if e2 then b2) I think the parentheses version is clearer. To me it's not as easy to picture what will happen when the condition is in the middle of the expression. Also in the above, is e1 evaluated before e? That would mean the result of e1 (a1 or b1) is thrown away if e if false. So looking at a few alternatives ... (e ? a : b) (e ? (e1 ? a1 : b1) : b) (e ? a : (e2 ? a2 : b2)) (e ? (e1 ? a1 : b1) : (e2 ? a2 : b2)) This better represents a decision tree I think. Each comparison gives one of two possible results which may be another comparison. Using keywords instead... (if e, a else b) (if e, (if e1, a1 else b1) else b) (if e, a else (if e2, a2 else b2)) (if e, (if e1, a1 else b1) else (if e2, a2 else b2)) (if e then a else b) (if e then (if e1 then a1 else b1) else b) (if e then a else (if e2 then a2 else b2)) (if e then (if e1 then a1 else b1) else (if e2 then a2 else b2)) or... possibly... (e selects a else b) (e selects (e1 selects a1 else b1) else b) (e selects a else (e2 selects a2 else b2)) (e selects (e1 selects a1 else b1) else (e2 selects a2 else b2)) I like this one, but maybe a shorter verb would be nice. Other possible words might be gives, chooses or picks. With the (e?a:b) syntax, I tend to want to switch the '?' and ':' here so that the colon is more consistent with how Python uses it. (e: a ? b) (e: (e1: a1 ? b1) ? b) (e: a ? (e2: a2 ? b2)) (e: (e1: a1 ? b1) ? (e2: a2 ? b2)) That may be more confusing to those who are use to 'C', but clearer to those who use Python as their main programming language. The '?' becomes an 'else' which might be useful in other expressions. Without the colon ... (e selects a ? b) (e selects (e1 selects a1 ? b1) ? b) (e selects a ? (e2 selects a2 ? b2)) (e selects (e1 selects a1 ? b1) ? (e2 selects a2 ? b2)) Or if e evaluates an integer... :-) (e selects a, b, c, ...) I think this would be quite useful and would work perfectly well with boolean expressions as well. The advantage here is that a,b,c etc.. would not be pre evaluated as they are when you use a list or dictionary. (e selects a, b) (e selects (e1 selects a1, b1), b) (e selects a, (e2 selects a2, b2)) (e selects (e1 selects a1, b1), (e2 selects a2, b2)) ( e selects (e1 selects a1, b1), (e2 selects a2, b2), (e3 selects a3, b3) ) Being able to have more than two alternative may reduce the need to nest or chain them in some cases. A variation might be to have negative index's pick from the far end just as list index's do. This would be my choice although I wasn't thinking of it when I started this reply. ;-) Cheers, Ron ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Michael Hudson wrote: Guido van Rossum [EMAIL PROTECTED] writes: Given the later addition of generator expressions with mandatory parentheses , the mandatory-parentheses version of a conditional expression looks less strange to me than it did then ;-). So I could happily use it even though I may still lean toward the other option 2 version (then-else) due to its not needing ':'s or a third elseif term for chaining. I think I'd prefer (if expr then expr else expre) i.e. no colons. My problem with this syntax is that it can be hard to read: return if self.arg is None then default else self.arg looks worryingly like return NAME NAME.NAME NAME NAME NAME NAME NAME NAME.NAME to me. But that's exactly what any language looks like if you get abstract enough: WORD WORD WORD WORD WORD WORD WORD And in fact, one read and understands your return statement just like an English sentence -- word by word from beginning to end. This seems an argument FOR the syntax not against.Moreover, if one uses the proposed parenthesized syntax, even the slightly odd word order of return if is mitigated. return (if self.arg is None then default else self.arg) None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. This is also true. *If* you want general community input, I would suggest a runoff ballot with those four choices (and a summary of pros and cons of each), or fewer if you see any as unacceptible. If there's one thing I've learned from the PEP 308 vote, it is that votes for language don't work. I prefer some discussion on Python-dev after which I pick one. Well, this is my input (and now I'm going to try and stay out of it). Cheers, mwh ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Adam wrote: So looking at a few alternatives ... [snip] (e ? (e1 ? a1 : b1) : (e2 ? a2 : b2)) [snip] (if e, (if e1, a1 else b1) else (if e2, a2 else b2)) [snip] (if e then (if e1 then a1 else b1) else (if e2 then a2 else b2)) [snip (e selects (e1 selects a1 else b1) else (e2 selects a2 else b2)) [snip] (e: (e1: a1 ? b1) ? (e2: a2 ? b2)) [snip] (e selects (e1 selects a1 ? b1) ? (e2 selects a2 ? b2)) [snip] (e selects (e1 selects a1, b1), (e2 selects a2, b2)) Please no more syntax proposals! There were enough in the PEP. It looks like most people support a conditional expression of some sort. We need to leave the syntax to Guido. We've already proved that like the decorators discussions, we can't as a community agree on a syntax. That's what we have a BDFL for. =) Steve -- You can wordify anything if you just verb it. --- Bucky Katt, Get Fuzzy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/21/05, Steven Bethard [EMAIL PROTECTED] wrote: Please no more syntax proposals! There were enough in the PEP. It looks like most people support a conditional expression of some sort. We need to leave the syntax to Guido. We've already proved that like the decorators discussions, we can't as a community agree on a syntax. That's what we have a BDFL for. =) Another QOTFcandidate! -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
I think I'd prefer (if expr then expr else expre) i.e. no colons. My problem with this syntax is that it can be hard to read: return if self.arg is None then default else self.arg looks worryingly like return NAME NAME.NAME NAME NAME NAME NAME NAME NAME.NAME That can already be written in Python: return self.arg or default And maybe the syntax of the future conditional operator could be extended so that: return self.arg else default Would be equivalent to the previous line. For stuff were a conditional expression really is needed, like in: return if self.arg then yes else no One would hope that whoever writes the conditional expression doesn't make the expressions so long and complicated that it looks like NAME NAME.NAME NAME... It doesn't matter which syntax proposal that wins, it will still be very tempting to write unreadable code with it (think nested/chained conditional expressions). That (and the fact that I've never felt a real need for a conditional expression thanks to the or operator) is my very humble argument against it. -- mvh Björn ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
BJörn Lindqvist [EMAIL PROTECTED] writes: My problem with this syntax is that it can be hard to read: return if self.arg is None then default else self.arg looks worryingly like return NAME NAME.NAME NAME NAME NAME NAME NAME NAME.NAME That can already be written in Python: No it can't! Would you believe I had this exact conversation two and a half years ago? :) return self.arg or default Consider what happens if self.arg is 0, here. Cheers, mwh -- If I had wanted your website to make noise I would have licked my finger and rubbed it across the monitor. -- signature of istartedi on slashdot.org ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido: When you invited resumed discussion, did you intend to proceed from where the revised PEP left off (with a few variations on the table), or to start over from point zero (with potentially anything and everything on the table). In particular, do we need to rehash the reasons for rejection of the backwards if-else proposal that a few seem to wish to resurrect? Many people, perhaps most, including me, read exp1 if exp2 else exp3 # as cond if etrue else efalse # in direct analogy with cond ? etrue : efalse # from C I mentally read ?: in C as if/else! It took a few readings of the proposal to even realize that it the order flipped. There there is the obvious analogy with Python's if cond: etrue else: efalse with 'if' moved over to the first : position (and the : then removed) but with 'else' still between the alternatives (and the second : also removed). Then there are conditional functions, in various languages, iff(cond, etrue, efalse), which as far as I know always have the expressions in that order. Need I continue? Or is the dead still dead? Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
I think a recap of past arguments is useful. Me-too votes are not. i will read everything and pick a syntax and that's it. We can do it in Python 2.5. On 9/21/05, Terry Reedy [EMAIL PROTECTED] wrote: Guido: When you invited resumed discussion, did you intend to proceed from where the revised PEP left off (with a few variations on the table), or to start over from point zero (with potentially anything and everything on the table). In particular, do we need to rehash the reasons for rejection of the backwards if-else proposal that a few seem to wish to resurrect? Many people, perhaps most, including me, read exp1 if exp2 else exp3 # as cond if etrue else efalse # in direct analogy with cond ? etrue : efalse # from C I mentally read ?: in C as if/else! It took a few readings of the proposal to even realize that it the order flipped. There there is the obvious analogy with Python's if cond: etrue else: efalse with 'if' moved over to the first : position (and the : then removed) but with 'else' still between the alternatives (and the second : also removed). Then there are conditional functions, in various languages, iff(cond, etrue, efalse), which as far as I know always have the expressions in that order. Need I continue? Or is the dead still dead? Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/guido%40python.org -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Steven Bethard wrote: Please no more syntax proposals! There were enough in the PEP. It looks like most people support a conditional expression of some sort. We need to leave the syntax to Guido. We've already proved that like the decorators discussions, we can't as a community agree on a syntax. That's what we have a BDFL for. =) No problem, I'll go back to watching this interesting discussion and see what happens. :-) I really should have deleted all but the last one anyway and probably should have moved it to python-list at that point since it's quite different from whats being proposed I think. Cheers, Ron ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Jim Jewett wrote: a very nice summary (3) What order should the clauses appear? (if test then True else False) (if test1 then Val1 elif test2 Val2 elif test3 Val3 else Val4) + Natural Order - do we need then? (True if normal else False) (Val1 if test1 else Val2 if test2 else Val3 if test3 else Val4) + Best order for normal/default conditionals + Best order in general if we weren't used to left-right processing - But we *do* expect left-right almost everywhere except assignments + out-of-order evaluation is already used in LC's and GE's + declarative style, rather than imperative To try and make that last point clearer: real = (z.real if isinstance(z, ComplexType) else z) This translates directly into in words as: Set real to be the real component of z if z is a complex number, otherwise set it to be the same as z vs. real = (if isinstance(z, ComplexType) then z.real else z) I can't put that into words without changing the order of the elements either by re-using the phrasing from above (with the condition between the two outcomes), or else describing the statement form instead of the expression form by bringing the condition all the way to the front: If z is a complex number, then set real to be the real component of z, otherwise set real to be the same as z I find it to be like with GE's and LC's - the phrasing works better with the expression at the front, because you say basically what you're doing, then you put the additional constraints on it (i.e., which iterable is used as the data source, and what filtering is applied to the elements of that iterable) I think I've said enough on this point though, so I'll try to bite my tongue until Guido makes a decision. . . Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.blogspot.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Ron Adam wrote: (a if e then b) ((a1 if e1 then b1) if e then b) (a if e then (a2 if e2 then b2)) ((a1 if e1 then b1) if e then (a2 if e2 then b2)) I think you mean 'else' rather than 'then' in all those, don't you? -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Greg Ewing wrote: Ron Adam wrote: (a if e then b) ((a1 if e1 then b1) if e then b) (a if e then (a2 if e2 then b2)) ((a1 if e1 then b1) if e then (a2 if e2 then b2)) I think you mean 'else' rather than 'then' in all those, don't you? Yes of course, thanks for correcting. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Gary Herron wrote: And in fact, one read and understands your return statement just like an English sentence -- word by word from beginning to end. This seems an argument FOR the syntax not against.Moreover, if one uses the proposed parenthesized syntax, even the slightly odd word order of return if is mitigated. The reason I like a if b else c is because it has the most natural word order. In English, My dog is happy if he has a bone, else sad. sounds much more natural than My dog is, if he has a bone, happy, else sad. In return statements, return self.arg if self.arg is not None else default looks quite all right to me. I think the fact that it does resemble English word order so much prevents the word-soup problem from occurring. Interestingly, it looks *more* odd to me if parens are included: return (self.arg if self.arg is not None else default) I think this is because, without the parens, I tend to read the if as applying to the whole phrase return self.arg, not just to the self.arg. The English analogy is rewriting My dog is happy if he has a bone as If he has a bone, my dog is happy, which also sounds natural, whereas My dog is, if he has a bone, happy sounds unnatural. So I still prefer a if b else c to any of the alternatives, and I still think parens should not be required. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: Given this realization, I'm now -1 on Raymond's idea, and +1 on adding a conditional expression. I believe (y if x else z) was my favorite last time, wasn't it? I've changed the subject accordingly. As the PEP states, I'm not sure if changing the customary order of arguments in conditional expressions is good. Also, I assume the thing will be short-circuiting, and it's confusing to grasp that y in (y if x else z) will possibly never be evaluated. Reinhold -- Mail address is perfectly valid! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Tue, Sep 20, 2005 at 09:04:53AM -0700, Guido van Rossum wrote: On 9/20/05, Michael Hudson [EMAIL PROTECTED] wrote: Guido van Rossum [EMAIL PROTECTED] writes: On 9/19/05, Raymond Hettinger [EMAIL PROTECTED] wrote: I propose that in Py3.0, the and and or operators be simplified to always return a Boolean value instead of returning the last evaluated argument. While you're at it, maybe we should switch to and || as well? That's another thing I always mistype when switching between languages... You're joking, surely? I wasn't, but I wasn't pushing for it either. Consider it withdrawn given the response. Also, this proposal needs to be considered together with the addition of a proper conditional operator, like x?y:z. I think this discussion has been had before, you know. Unfortunately, if we were to accept Raymond's proposal, we'd have to revisit the discussion, since his proposal removes several ways we currently avoid the need. In fact, I think Raymond's example is more properly considered an argument for adding a conditional expression than for removing the current behavior of the and/or shortcut operators; had we had a conditional expression, he wouldn't have tried to use the x and y or z syntax that bit him. Given this realization, I'm now -1 on Raymond's idea, and +1 on adding a conditional expression. I believe (y if x else z) was my favorite last time, wasn't it? I've changed the subject accordingly. I'm +1 for allowing authors to write return bool(thing or default) when they mean a function to return a bool. I had the privilege of working in a large base of perl code (a learning experience) and while some engineers abused functions that were documented as only returning true/false by depending on the side effects of 'and' and 'or' this was easily fixed. The functions were changed to literally return a plain true or false value and those engineers were summarily fired. I'm a dependable Hettinger fanboy but on this one I have to agree with the we're-all-adults club. Let the authors type an extra few chars if they want to make the code match the intent. -jackdied ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] In fact, I think Raymond's example is more properly considered an argument for adding a conditional expression than for removing the current behavior of the and/or shortcut operators; had we had a conditional expression, he wouldn't have tried to use the x and y or z syntax that bit him. I agree. Given this realization, I'm now -1 on Raymond's idea, There are a lot of people who use 'or', especially, as intended. and +1 on adding a conditional expression. I believe (y if x else z) was my favorite last time, wasn't it? No. That was your original proposal, which you later rejected. The original version of this PEP proposed the following syntax: expression1 if condition else expression2 The out-of-order arrangement was found to be too uncomfortable for many of participants in the discussion; especially when expression1 is long, it's easy to miss the conditional while skimming. Your final 'favorite' was apparently (at the top) Proposal The proposed syntax is as follows: (if condition: expression1 else: expression2) (+ elif parts) selected from Summary of the Current State of the Discussion Groups are falling into one of three camps: 1. Adopt a ternary operator built using punctuation characters: condition ? expression1 : expression2 2. Adopt a ternary operator built using new or existing keywords. The leading examples are: condition then expression1 else expression2 (if condition: expression1 else: expression2) 3. Do nothing. Given the later addition of generator expressions with mandatory parentheses , the mandatory-parentheses version of a conditional expression looks less strange to me than it did then ;-). So I could happily use it even though I may still lean toward the other option 2 version (then-else) due to its not needing ':'s or a third elseif term for chaining. *If* you want general community input, I would suggest a runoff ballot with those four choices (and a summary of pros and cons of each), or fewer if you see any as unacceptible. Terry J. Reedy -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/python-python-dev%40m.gmane.org ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/20/05, Terry Reedy [EMAIL PROTECTED] wrote: Guido van Rossum [EMAIL PROTECTED] wrote in message and +1 on adding a conditional expression. I believe (y if x else z) was my favorite last time, wasn't it? No. That was your original proposal, which you later rejected. Thanks for setting me straight; upon re-reading the PEP I couldn't even remember which one I favored at the time! Your final 'favorite' was apparently (at the top) Proposal The proposed syntax is as follows: (if condition: expression1 else: expression2) (+ elif parts) selected from Summary of the Current State of the Discussion Groups are falling into one of three camps: 1. Adopt a ternary operator built using punctuation characters: condition ? expression1 : expression2 2. Adopt a ternary operator built using new or existing keywords. The leading examples are: condition then expression1 else expression2 (if condition: expression1 else: expression2) 3. Do nothing. Given the later addition of generator expressions with mandatory parentheses , the mandatory-parentheses version of a conditional expression looks less strange to me than it did then ;-). So I could happily use it even though I may still lean toward the other option 2 version (then-else) due to its not needing ':'s or a third elseif term for chaining. I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. *If* you want general community input, I would suggest a runoff ballot with those four choices (and a summary of pros and cons of each), or fewer if you see any as unacceptible. If there's one thing I've learned from the PEP 308 vote, it is that votes for language don't work. I prefer some discussion on Python-dev after which I pick one. -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
At 12:17 PM 9/20/2005 -0700, Guido van Rossum wrote: I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. +1, despite the fact that we seem on a slippery slope towards becoming a kind of infix Lisp. ;) Between (yield x), (x for x in y), and now (if x then y else z), it seems that parentheses are all the rage now. Will we get (try expr finally expr) next? 0.5 wink *If* you want general community input, I would suggest a runoff ballot with those four choices (and a summary of pros and cons of each), or fewer if you see any as unacceptible. If there's one thing I've learned from the PEP 308 vote, it is that votes for language don't work. I prefer some discussion on Python-dev after which I pick one. Also +1. :) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/20/05, Phillip J. Eby [EMAIL PROTECTED] wrote: At 12:17 PM 9/20/2005 -0700, Guido van Rossum wrote: I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. +1, despite the fact that we seem on a slippery slope towards becoming a kind of infix Lisp. ;) Between (yield x), (x for x in y), and now (if x then y else z), it seems that parentheses are all the rage now. Will we get (try expr finally expr) next? 0.5 wink +1 from me as well. The use will be much more obvious to a newbie than ``expr ? expr : expr``. And I have used the syntactic-heavy listcomps in Haskell and I must say that Python's version is much nicer. I like the wordy version. =) *If* you want general community input, I would suggest a runoff ballot with those four choices (and a summary of pros and cons of each), or fewer if you see any as unacceptible. If there's one thing I've learned from the PEP 308 vote, it is that votes for language don't work. I prefer some discussion on Python-dev after which I pick one. Also +1. :) +1 from me, although I sure got lambasted by some people when I said I liked this style during the whole decorator debate. =) -Brett ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. FWIW, I find this quite intuitive. It follows the same pattern as LCs and GEs -- remove the colons and add parentheses (or brackets for LCs). So I'm +1. STeVe -- You can wordify anything if you just verb it. --- Bucky Katt, Get Fuzzy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
(Adding python-dev back to the CC list) On 9/20/05, Jason Orendorff [EMAIL PROTECTED] wrote: If there's one thing I've learned from the PEP 308 vote, it is that votes for language don't work. I prefer some discussion on Python-dev after which I pick one. +1 Some visual aids: return (if q: q.popleft() else: None) return (if q then q.popleft() else None) return q ? q.popleft() : None Hmmm. Score one for ?:. But: Why? Just because it's shorter? menu.append( if gotHerring(): popHerring() elif gotAnyFish(): popAnyFish() else: Tofurbot()) menu.append(gotHerring() ? popHerring() : gotAnyFish() ? popAnyFish() : Tofurbot()) Here, I like the way the verbose syntax politely spreads itself out over multiple lines. In C, I never know where to put the line breaks. Ouch. You're bringing up another valid issue: whether to support elif. I think if we go with (if ... then ... else ...) or (if ...: ... else: ...) we'll have to support elif as well: (if ... then ... elif ... then ... else ...) or (if ...: ... elif ...: ... else: ...) I really don't like the latter. Here's a suggestion for a way to decide between a wordy version or C-style ?: -- if we abandon and/or in favor of /||, we should also go with ?:; if we keep and/or, we should use a keyword-based conditional as well. Since so far the feedback is overwhelmingly in favor of keeping and/or, I think that settles the case in favor of a wordy version. My preference then would be (if ... then ... elif ... then ... else ...) which gives my a nice nostalgic feeling because (except for the elif part) Algol-60 had the same thing -- the first programming language I ever learned. :) (Oh, and a way to decide between colon or no colon: we're not using colons in list comps and genexprs either.) -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Tue, 2005-09-20 at 17:40, Guido van Rossum wrote: Ouch. You're bringing up another valid issue: whether to support elif. I think if we go with (if ... then ... else ...) or (if ...: ... else: ...) we'll have to support elif as well: I'm not so sure. Once you start writing such a complicated thing, I think readability will favor just breaking the code out into traditional if-blocks. I'd be happy enough with just a binary condition. -Barry signature.asc Description: This is a digitally signed message part ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On 9/20/05, Terry Reedy [EMAIL PROTECTED] wrote: Given the later addition of generator expressions with mandatory parentheses , the mandatory-parentheses version of a conditional expression looks less strange to me than it did then ;-). So I could happily use it even though I may still lean toward the other option 2 version (then-else) due to its not needing ':'s or a third elseif term for chaining. I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. I presume this revision would continue to include elif clauses. If I put on a 'designing Python for everyone' hat, then the presence of the leading 'if' looks better than the slightly-too-cute (especially for Python) abbreviated version. +1 *If* you want general community input, I would suggest a runoff ballot with those four choices (and a summary of pros and cons of each), or fewer if you see any as unacceptible. If there's one thing I've learned from the PEP 308 vote, it is that votes for language don't work. I prefer some discussion on Python-dev after which I pick one. If we reject both the status quo and the symbol-tax form and agree on the above as the best wordy form, then it is a moot point anyway ;-) C.l.p. newcomers continue to periodically request How do I write conditional expressions?. I think most will be happier with something clear and readable. Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On 9/20/05, Guido wrote: On 9/20/05, Jason Orendorff [EMAIL PROTECTED] wrote: return (if q: q.popleft() else: None) return (if q then q.popleft() else None) return q ? q.popleft() : None Hmmm. Score one for ?:. Why? Just because it's shorter? Just a gut response to the look. The verbose forms strike me as cluttered in this particular case. In the multiline case, it doesn't look like clutter because the if/elif/else bits line up, which fits the way Python has already trained my brain. (Oh, and a way to decide between colon or no colon: we're not using colons in list comps and genexprs either.) (grin) Easily fixed: print average weight:, avg(for c in chefs: c.weight) rdict = dict(for k, v in D.iteritems(): v, k) Honestly, I think I would prefer this syntax. Examples from real code, before and after: lines = [line for line in pr.block.body if line.logical_line.strip() != ''] lines = [for line in pr.block.body: if line.logical_line.strip() != '': line] row.values = \ [line[col.start:col.end].strip() for col in columns] row.values = \ [for col in columns: line[col.start:col.end].rstrip()] return [p for p in self.listdir(pattern) if p.isdir()] return [for p in self.listdir(pattern): if p.isdir(): p] -j ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Steven Bethard wrote: Guido van Rossum wrote: I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. FWIW, I find this quite intuitive. It follows the same pattern as LCs and GEs -- remove the colons and add parentheses (or brackets for LCs). So I'm +1. *But*, in LC's and GE's, the body of the main clause of the statement is also pulled out and placed in front of the keyword: def gen(): for VAR in ITERABLE: if COND: yield EXPR becomes: gen = (EXPR for VAR in ITERABLE if COND) This makes sense to me, because the most important thing in the generator expression is the way each element is populated - the source iterable and the filtering condition do matter, but they aren't as important. It also makes the expression forms more declarative in nature, rather than being procedural statements embedded inside an expression. Notice also that, in this case, if ITERABLE is empty, or COND always evaluates false in boolean context, then EXPR is never executed - in other words, Python already has precedent for out of order code execution in expression evaluation. Guido's original PEP 308 proposal worked much the same way: if COND: x = EXPR1 else: x = EXPR2 became: x = (EXPR1 if COND else EXPR2) I see this as similar in spirit to the current form of LC's and GE's - the most important things are the two possible values rather than the condition for choosing between them, and this form makes them clearly visible at the start and end of the expression, rather than embedding one of them in the middle. The post-filtered form is also similarly declarative rather than procedural. This version doesn't need a separate 'elif' form - elif can be written as: x = (EXPR1 if COND1 else EXPR2 if COND2 else EXPR3) Note that the keyword count is no higher than if 'elif' was used, because the 'then' keyword isn't needed: x = (if COND1 then EXPR1 elif COND2 then EXPR2 else EXPR3) Here's Raymond's problematic example using this original PEP 308 form: def real(self): 'Return a vector with the real part of each input element' # do not convert integer inputs to floats return self.map(lambda z: (z.real if type(z)==types.ComplexType else z)) And the other non-colon, keyword based proposal in PEP 308's top four: def real(self): 'Return a vector with the real part of each input element' # do not convert integer inputs to floats return self.map(lambda z: (if type(z)==types.ComplexType then z.real else z)) Another common use case would be for mutable default arguments: x = ([] if arg is None else list(arg)) x = (if arg is None then [] else list(arg)) Basically, I'm +1 on the original PEP 308 form because it reads more naturally (and more like LC's and GE's) to me in expression contexts, and +0 on the if/then/elif/else form (because I would like a real conditional operator). Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.blogspot.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: I think I'd prefer (if expr then expr else expre) i.e. no colons. None of the other expression forms (list comprehensions and generator expressions) involving statement keywords use colons. While I like the looks of the form without colons better, I can't quite follow this argument for it. In LCs and GEs, colons wouldn't make any sense in the first place because the expression controlled by for and if is written before it: [expression(x) for x in y]. Just where would anyone put a colon there, anyway? A colon does make sense if something follows it, as is currently the case in lambda expressions. It would also be the case in an (if x: y else: z) form. I have a feeling that trying to make all expression forms which happen to use statement keywords colon-free is seeking an artificial consistency. I'm happy to be proven wrong, though. +1 on the idea of introducing a conditional expression in the first place, though. -- Thomas ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Barry Warsaw wrote: I'm not so sure. Once you start writing such a complicated thing, I think readability will favor just breaking the code out into traditional if-blocks. I'd be happy enough with just a binary condition. Nothing prevents you from spreading the code over multiple lines, like so: x = (if a then b elif c then d else e) or even x = (if a then b elif c then d else e ) especially as there are going to be parentheses around the whole thing anyway. From a readability point of view, this is no different from if-statement blocks, and the matter is IMO not worth dumbing down an if-expression thingy as compared to its if-statement companion. -- Thomas ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Tue, 2005-09-20 at 18:21, Thomas Lotze wrote: Nothing prevents you from spreading the code over multiple lines, like so: x = (if a then b elif c then d else e) or even x = (if a then b elif c then d else e ) especially as there are going to be parentheses around the whole thing anyway. From a readability point of view, this is no different from if-statement blocks, and the matter is IMO not worth dumbing down an if-expression thingy as compared to its if-statement companion. I guess that's my point. To me, your latter is actually worse than if a: x = b elif c: x = d else: x = e I think the conditional stuff gets the most bang for the buck in situations like: d[foo] = if a then b else c -Barry signature.asc Description: This is a digitally signed message part ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Barry Warsaw wrote: x = (if a then b elif c then d else e ) [...] I guess that's my point. To me, your latter is actually worse than if a: x = b elif c: x = d else: x = e Can't see a difference as far as readability is concerned. But then, tastes differ. I think the conditional stuff gets the most bang for the buck in situations like: d[foo] = if a then b else c And I think similar holds for LCs and GEs. Unwinding a complex sequence of for and if clauses is certainly no fun unless one is really used to it. (Which doesn't take long, though.) But your example poses another question: Up until now, I had the impression that parentheses should be mandatory around a conditional expression. There's certainly no avoiding them in situations like (if x then 1 else 2) + 3. But what about unambiguous cases like your example line? -- Thomas ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Wed, 21 Sep 2005, Thomas Lotze wrote: Barry Warsaw wrote: x = (if a then b elif c then d else e ) [...] I guess that's my point. To me, your latter is actually worse than if a: x = b elif c: x = d else: x = e Can't see a difference as far as readability is concerned. But then, tastes differ. [...] With the former, we have a more C-style syntax where meaning is determined purely by delimeters rather than by whitespace. Instead of braces '{' and '}', we have 'then' and 'elif'/'else'. That's a real difference. The stricter form where you don't allow 'elif' will get used in more restricted circumstances, so gives less encouragement for widespread abuse of conditional expressions by people who don't like whitespace-based syntax. John ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
On Tue, 20 Sep 2005, John J Lee wrote: [...] With the former, we have a more C-style syntax where meaning is determined purely by delimeters rather than by whitespace. Instead of braces '{' and '}', we have 'then' and 'elif'/'else'. That's a real difference. [...] Um, not clear, sorry: the real difference I meant to refer to above is that between delimiter-based and whitespace-based syntaxes (and not between braces and differently-spelled delimiters). John ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
John J Lee [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The stricter form where you don't allow 'elif' will get used in more restricted circumstances, so gives less encouragement for widespread abuse of conditional expressions by people who don't like whitespace-based syntax. I think 'abusiveness' is somewhat in the eye of the beholder here. In any case, without 'elif', one could still chain expressions by writing x = (if a then b else (if c then d else e)) which is even more Lispish. I personally think one () is enough and prefer x = (if a then b elif c then d else e) which is similar to how I wrote such things in C. Elif has the same justification here as with the statement form, where it is also unnecessary but saves nesting levels. Terry J. Reedy ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Terry Reedy wrote: The original version of this PEP proposed the following syntax: expression1 if condition else expression2 The out-of-order arrangement was found to be too uncomfortable for many of participants in the discussion; especially when expression1 is long, it's easy to miss the conditional while skimming. Guido wrote that while he was in listen-to-the-masses mode. If he's switched back to follow-my-instincts mode, it may need to be re-evaluated. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Adding a conditional expression in Py3.0
Guido van Rossum wrote: I think if we go with (if ... then ... else ...) or (if ...: ... else: ...) we'll have to support elif as well: (if ... then ... elif ... then ... else ...) or (if ...: ... elif ...: ... else: ...) One nice thing about x if b else y is that it chains without needing any more keywords: x if b else y if c else z But if you require parens, it's not so nice: (x if b else (y if c else z)) -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com