[Python-ideas] Inline assignments using "given" clauses
Steven D'Aprano
steve at pearwood.info
Sun May 13 12:04:31 EDT 2018
On Sat, May 12, 2018 at 08:06:02PM -0400, Neil Girdhar wrote:
> On Sat, May 12, 2018 at 2:28 PM Steven D'Aprano <steve at pearwood.info> wrote:
> > > * there are no difficult mental questions about evaluation order, e.g.,
> > > in a bracketed expression having multiple assignments.
> >
> > Aren't there just?
> >
> > x = 1
> > print( x + x given x = 50 )
> >
> >
> > Will that print 100, or 51? Brackets ought to make it clearer:
> >
> > (x + x given x = 50) # this ought to return 100
> > x + (x given x = 50) # this ought to return 51
> >
> > but if I leave the brackets out, I have no idea what I'll get.
> >
>
> It has to be 100, or else outer parentheses change how an expression is
> evaluated.
Whether that it right or wrong, you're missing the point. You said that
we don't have to care about evaluation order. But we do: even if your
analysis is correct, not everyone will realise it. I didn't.
And I still don't, because I think your analyse is wrong.
"Outer parentheses" is a red herring. I should have written:
(x + x) given x = 50 # this ought to return 100
x + (x given x = 50) # this ought to return 51
and now there are no outer parentheses to worry about. The question is
now whether "given" binds more tightly than + or not.
We get to choose the precedence, and whatever we choose, it will
surprise (or annoy) some people, and more importantly, some people
simply won't know, and will have to ponder the difficult question of
what the evaluation order is.
This is already true today with code that has side-effects. I can
simulate "given" using exec. It only works in the module scope:
# another_expr given target = expr
exec("target = expr") or another_expr
but now we can see how precedence makes a real difference:
x = 1
x + (exec("x = 50") or x)
versus:
x = 1
exec("x = 50) or (x + x)
Regardless of which behaviour we choose, some people won't know it and
will have to deal with "difficult mental questions about evaluation
order".
That's unavoidable, regardless of how we spell it, := or "given".
--
Steve
More information about the Python-ideas
mailing list