Some syntactic sugar proposals

Ian Kelly ian.g.kelly at
Tue Nov 16 17:16:52 CET 2010

On 11/16/2010 3:42 AM, Steven D'Aprano wrote:
> On Mon, 15 Nov 2010 22:40:00 -0700, Ian Kelly wrote:
>> On 11/15/2010 10:26 PM, Steven D'Aprano wrote:
>>> t = foo()+bar()+baz() if pred(it) else baz()-foo()-bar()
>>> What does "it" mean here?
>> "it" would mean the result of the expression foo()+bar()+baz().  What
>> else could it mean?
> It could mean the last expression, baz(). Or the entire compound
> expression, foo()+bar()+baz().

Unless the precedence rules were to change, the three expressions in the 
example that are operated on by the ternary are these:

1. foo()+bar()+baz()
2. pred(it)
3. baz()-foo()-bar()

So the antecedent would have to be one of those in order to make any 
sense at all, and obviously the only choice of those that would be 
useful is the first one.

>> There are valid objections to the proposal, but the
>> intended semantics seem perfectly clear.
> Fair point, my example was terrible and didn't show the point that was
> clear in my head. Mea culpa. How about this instead?
> t = foo()+it if pred(it) else bar()
> Should that be a SyntaxError, or is `it` a variable that holds its value
> from statement to statement?

SyntaxError.  Implementing this without making 'it' a keyword would be 
very sloppy, IMO.

Another option would be to use a special variable named '__', similar to 
the variable '_' that the REPL uses to store the result of the last 
command.  This might break some existing code, but probably not very 
much.  Mostly it would just be confusing.

> t = (foo() if pred(it) else bar()) if cond(it) else baz()

More problematic:

t = foo() if pred(bar() if pred2(it) else str(it)) else bar()

Does the first 'it' belong to the inner or outer ternary?  Probably the 
inner one.  What about the second 'it'?

> BTW, I frequently use "it" for iterators, and making "it" a reserved word
> would break a lot of my code. This would make me quite peeved.

I do the same, and yes, it would make upgrading a real pain.


More information about the Python-list mailing list