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

Nick Coghlan ncoghlan at gmail.com
Mon Jan 16 15:15:05 CET 2012

```On Mon, Jan 16, 2012 at 5:46 AM, Paul Moore <p.f.moore at gmail.com> wrote:
>> In summary, again, I think we should support proper quantifications.
>
> I'm getting more comfortable with the idea, but I think it needs a bit
> more discussion to come up with something that fits in cleanly with
> the rest of Python, while still adding the value you want.

Indeed.

With the clarification that my original "long form" expansion was
incorrect (since it only looped over the outer set once), I'll put
forward a slightly shorter variant of Guido's expansion (as someone
else already noted, next() can be a useful alternative to pop() if you
aren't keeping the original set around)

_sentinel = object()
while True:
p1 = next((p for (s0,p1) in decisions if s0==slot_num), _sentinel)
if p1 is _sentinel:
break

for p2 in {p2 for (s0,p2) in proposals if s0==slot_num and p2 != p1}:
...

So, let's consider this proposal:

"some VAR in ITERABLE if COND" would be an expression that:

1. *deliberately* leaks the variable into the surrounding scope
(embedded assignment ahoy)
2. Defines the expression value roughly as follows:

_itr = (VAR for VAR in ITERABLE if COND) # i.e. it's an implicit
generator expression
try:
VAR = next(_itr)
except StopIteration:
_expr_result = False
else:
_expr_result = True

And, further suppose, that we finally cave on allowing a filter clause
in for statements

Then Annie's original example would look like this:

while some s0, p1 in decisions if s0==slot_num:
for s0, p2 in proposals if s0==slot_num and p2 != p1:
...

And, since we *know* anything even vaguely resembling an embedded
assignment syntax would almost immediately be adopted for any-and-all
of the various embedded assignment requests we've seen over the years,
here's how it would look for the regex use case:

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

Hmm, still doesn't feel right to me - trying to shove a square peg
(mathematical quantification) into a round hole (Python's syntax). In
particular, the any()/all() way of doing things avoids the double-if
problem when used in an if statement, whereas the version that
captures the variable (and hence moves the predicate to the end) reads
very strangely in that case.

Removing the if clause doesn't help, since you can easily add it back
by using a generator expression as your iterable.

Cheers,
Nick.

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

```