[Python-ideas] Inline assignments using "given" clauses

Steven D'Aprano steve at pearwood.info
Sun May 13 10:55:03 EDT 2018


On Sun, May 13, 2018 at 12:10:08AM -0400, Neil Girdhar wrote:

> > > Suppose you have a generator like
> > >
> > > (expression(f(x), y, z)
> > >  for x in xs
> > >  for y in ys(x)
> > >  for z in zs(y))
> > >
> > > With given notation you can optimize:

Actually, as you admitted, you can't, since this isn't part of 
the proposed syntax or semantics. But let's put that aside.

> > > (expression(f_x, y, z)
> > >  for x in xs
> > >  given f_x = f(x)
> > >  for y in ys(x)
> > >  for z in zs(y))
> > >
> > > whereas with :=, you can't.

Except of course you can:

> >     (expression(f_x, y, z) for x in xs
> >          for y in ys(x)
> >          for z in zs(y)
> >          if (f_x := f(x)) or True)
> >          )

[Neil]
> My thought is that if each component is simple enough *and* if each
> component can be reasoned about independently of the others, then it's
> fine.  The issue I had with the := code you presented was that it was
> impossible to reason about the components independently from the whole.

I said it was rubbish code which I wouldn't use for serious work. But 
"impossible" to reason about? That's pretty strong, and definite, words 
for something which is actually pretty easy to reason about.

    (expression(f_x, y, z) for x in xs
         for y in ys(x)
         for z in zs(y)
         if (f_x := f(x)) or True)
         )

I'm pretty sure you can reason about "expression(f_x, y, z)" on its own. 
After all, the above code was (apart from the := line) your own example. 
If you can't even reason about your own examples, you're in a bad place.

I think you can reason about the three for-loops "for x in xs" etc on 
their own. Again, they were your idea in the first place.

I expect you can reason about "if <clause> or True" on its own. It's a 
pretty basic Python technique, to call <clause> for its side-effect 
without caring about its return value.

Not something I would use for serious work, but this is YOUR example, 
not mine, so if you hate this generator expression, you were the one who 
suggested it.

Only the <clause> is new or different from ordinary Python code that 
works now:

    f_x := f(x)

The semantics of := are pretty damn simple (at least from the high-level 
overview without worrying about precedence or possible scoping issues):

    - evaluate f(x)
    - assign that value to f_x
    - return the value of f_x

which is EXACTLY THE SAME SEMANTICS OF "f_x given f_x = f(x)":

    - evaluate f(x)
    - assign that value to f_x
    - return the value of f_x

And you would reason about them the same way.



-- 
Steve


More information about the Python-ideas mailing list