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

Chris Angelico rosuav at gmail.com
Wed May 30 13:50:48 EDT 2018


On Thu, May 31, 2018 at 1:23 AM, Peter O'Connor
<peter.ed.oconnor at gmail.com> wrote:
>>  In comparison, I think that := is much simpler.
>
>
> In this case that's true, but a small modification:
>
>         updates = {
>             y: do_something_to(potential_update)
>             for x in need_initialization_nodes
>             for y in [x, *x.synthetic_inputs()]
>             if potential_update is not None
>             given potential_update = command.create_potential_update(y)
>             }
>
> Shows the flexibility of this given syntax vs ":="

I don't understand what you're showcasing here. With :=, you give a
name to something at the exact point that it happens:

        updates = {
            y: do_something_to(potential_update)
            for x in need_initialization_nodes
            for y in [x, *x.synthetic_inputs()]
            if (potential_update :=
command.create_potential_update(y)) is not None
            }

Personally, I'd use a shorter name for something that's used in such a
small scope (same as you use one-letter "x" and "y"). But that's the
only way that the 'given' syntax looks at all better - by encouraging
you to use yet another line, it conceals some of its immense
verbosity. (Note how the name "potential_update" is used twice with
:=, once to set and one to retrieve; but with given, it's used three
times - retrieve, retrieve, and set.)

How does this show that 'given' is more flexible?

ChrisA


More information about the Python-ideas mailing list