[Python-ideas] A real life example of "given"

Peter O'Connor peter.ed.oconnor at gmail.com
Thu May 31 08:22:21 EDT 2018

On Thu, May 31, 2018 at 1:55 PM, Neil Girdhar <mistersheik at gmail.com> wrote:

> Why wouldn't you want to just put the outer given outside the entire
> comprehension?
>     retval = [expr(name, x) given name=update(name, x) for x in seq]
> given name=something

There seems to be a lot of controversy about updating variables defined
outside a comprehension within a comprehension.  Seems like it could lead
to a lot of bugs and unintended consequences, and that it's safer to not
allow side-effects of comprehensions.

> The more I think about it, the more i want to keep "given" in
> comprehensions, and given in expressions using parentheses when given is
> supposed to bind to the expression first.

I think the problem is that you given to be used in two ways:
-  You want "B given A" to mean "execute A before B" when B is a simple
- "given A B" to mean "execute A before B" when B is a loop declaration.

The more I think about it, the more I think comprehensions should be parsed
in reverse order: "from right to left".  In this alternate world, your
initial example would have been:

           potential_updates = {
   (1)                          y: command.create_potential_update(y)
   (2)                          if potential_update is not None
   (3)                          given potential_update =
   (4)                          for y in [x, *x.synthetic_inputs()]
   (5)                          for x in need_initialization_nodes

Which would translate to:

           potential_updates = {}
    (5)  for x in need_initialization_nodes:
    (4)       for y in [x, *x.synthetic_inputs()]:
    (3)           potential_update = command.create_potential_update(y)
    (2)           if potential_update is not None:
    (1)               potential_updates[y] = command.create_potential_

And there would be no ambiguity about the use of given.  Also, variables
would tend to be used closer to their declarations.

But it's way to late to make a change like that to Python.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180531/dbc49b8c/attachment.html>

More information about the Python-ideas mailing list