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

Nick Coghlan ncoghlan at gmail.com
Sat May 5 12:06:54 EDT 2018

On 4 May 2018 at 22:06, Nick Coghlan <ncoghlan at gmail.com> wrote:

> (Note: Guido's already told me off-list that he doesn't like the way this
> spelling reads, but I wanted to share it anyway since it addresses one of
> the recurring requests in the PEP 572 discussions for a more targeted
> proposal that focused specifically on the use cases that folks had agreed
> were reasonable potential use cases for inline assignment expressions.
> I'll also note that another potential concern with this specific proposal
> is that even though "given" wasn't used as a term in any easily discovered
> Python APIs back when I first wrote PEP 3150, it's now part of the
> Hypothesis testing API, so adopting it as a keyword now would be markedly
> more disruptive than it might have been historically)

Since I genuinely don't think this idea is important enough to disrupt
hypothesis's public API, I've been pondering potential synonyms that are
less likely to be common in real world code, while still being
comprehensible and useful mnemonics for the proposed functionality.

The variant I've most liked is the word "letting" (in the sense of "while
letting these names have these values, do ..."):

    # Exactly one branch is executed here
    if m letting m = pattern.search(data):
    elif m letting m = other_pattern.search(data)):

    # This name is rebound on each trip around the loop
    while m letting m = pattern.search(remaining_data):

    # "f(x)" is only evaluated once on each iteration
    result = [(x, y, x/y) for x in data if y letting y = f(x)]

    # Tim's "bind two expressions" example
    if diff and g > 1 letting diff = x - x_base, g = gcd(diff, n):
        return g

    # The "bind two expressions" example across multiple lines
    while diff and g > 1 letting (
        diff = x - x_base,
        g = gcd(diff, n),
        ... # Do something with diff and g


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180506/45c3d344/attachment-0001.html>

More information about the Python-ideas mailing list