[Python-ideas] A comprehension scope issue in PEP 572
tim.peters at gmail.com
Mon May 7 15:02:36 EDT 2018
>> In a different thread I noted that I sometimes want to write code like
>> while any(n % p == 0 for p in small_primes):
>> # divide p out - but what's p?
>> But generator expressions hide the value of `p` that succeeded, so I
>> can't. `any()` and `all()` can't address this themselves - they
>> merely work with an iterable of objects to evaluate for truthiness,
>> and know nothing about how they're computed. If you want to identify
>> a witness (for `any()` succeeding) or a counterexample (for `all()`
>> failing), you need to write a workalike loop by hand.
[Brendan Barnwell <brenbarn at brenbarn.net>]
> I agree that is a limitation, and I see from a later message in the
> thread that Guido finds it compelling, but personally I don't find that that
> particular case such a showstopper that it would tip the scales for me
> either way. If you have to write the workalike look that iterates and
> returns the missing value, so be it. That's not a big deal.
Guido didn't find it compelling: for that specific example to show
`p` would require that for-loop targets "leak", and he remains opposed
to that. I don't want that changed either.
The issue instead is what the brand-new proposed ":=" should do, which
isn't used in that example at all. Whether that specific example can
be written in 500 other ways (of course it can) isn't really relevant.
One of the ironies already noted is that PEP 572 gives an example of
something that _won't_ work ("progressive_sums") which happens to be
the very use case that started the current debate about assignment
expressions to begin with. That raises the very same issue about ":="
that "the obvious" rewrite of my example at the top raises. Which
suggests to me (& apparently to Guido too) that there may be a real
issue here worth addressing.
There are many use cases for binding expressions outside of
synthetically generated functions. For PEP 572, it's the totality
that will be judged, not just how they might work inside list
comprehensions and generator expressions (the only topics in _this_
particular thread), let alone how they work in one specific example.
More information about the Python-ideas