[Python-ideas] Fwd: quantifications, and tuple patterns

Nick Coghlan ncoghlan at gmail.com
Tue Jan 17 12:16:39 CET 2012

On Tue, Jan 17, 2012 at 3:39 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> Paul Moore wrote:
>> On 16 January 2012 14:47, Devin Jeanpierre <jeanpierreda at gmail.com> wrote:
>>> You can always add a full-on assignment-as-expression, if you're
>>> concerned about that.
>>>   if (m := pat.search(data)) is not None:
>>> Also, the keyword doesn't have to be "if". I've always read the bar as
>>> "such that" or "where".
>> I suggested that a while back in this thread (in the form of any(var
>> := val for val in itr if pred)). It didn't get much traction
> In the matter of := being used for assignment-as-expression... +1!

Assignments as expressions aren't all that easy to use in the "some"
case that started the thread, and the reason is the same as the reason
iteration variables in comprehensions don't leak into the surrounding
scope any more: generator expressions and comprehensions create their
own scope, separate from that of the containing function.

If Python ever did get assignment expressions, the most likely
candidate would actually be based on the existing use of "as" for
naming (or renaming) things:

    if (pat.search(data) as m) is not None:

    while (next(p1 for (s0, p1) in decisions if s0==slot_num, None) as
p1) is not None:

However, assignments as expressions are still a long way from being
shown to ever improve clarity enough to be worth the additional
language complexity.

Getting back specifically to the quantification question, I wonder if
being able to explicitly export an iteration variable from a
comprehension might work:

    while any(s0 == slot_num for (s0, some p1) in decisions):

Abusing it for embedded assignments is still ugly, but at least
vaguely comprehensible once you're familiar with the meaning of

    if any(m is not None for some m in [pattern.search(data)]):

(As far as how that could actually work goes, with the bindings
limited to simple names, as they are for iteration variables, you
could probably just make the relevant mapping available inside the
comprehension for class and module namespaces and make use of the
nonlocal machinery for function namespaces)

I still can't honestly say I like the idea, but I at least dislike it
less than anything else I've seen in the thread so far :)


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list