[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Python-Dev] Call for prudence about PEP-572

On 7/7/2018 12:53 PM, Tim Peters wrote:
> [Guido]
>     ...
>     As to why you might want to use := in a function call, I could
>     imagine writing
>      ??? if validate(name := re.search(pattern, line).group(1)):
>      ??????? return name

If name has to be non-blank to pass validate, one can avoid the 
assignment within the function call be adding a redundant pre-test.

if name := re.search(pattern, line).group(1) and validate(name):
     return name

Giampaolo would presumably prefer this, but I don't think such 
preference should be enforced on everyone.

If name == '' is valid, then the alternative is the current one, using a 
separate assignment statement.

name = re.search(pattern, line).group(1)
if validate(name):
     return name

> When I was staring at my code, I never mentioned the very first 
> plausible use I bumped into (in code I was actively working on at the time):
> while not probable_prime(p := randrange(lo, hi)):
>  ? ? ?pass
> # and now `p` is likely a random prime in range

As long as lo excludes 0:

while p := randrange(lo, hi) and not probable_prime(p):

I can see how someone might prefer this stylistically, but it is buggy. 
If this is contained in a function (very likely) and lo could be <= 0, 
because it is either passed in or calculated, 0 could be passed on a 
likely prime!
> I never mentioned it because I expected it would annoy people on 3(!) 
> counts:
> - assigning in a function call

This is a style preference that people can and will disagree on.  In any 
case, I think correctness trumps beauty, just as it trumps speed.

> - reducing the loop body to `pass`

I fixed that ;-).  'continue' better expresses the 'try again' part of 
English versions, such as "While the trial value is not acceptable, try 

> - using the binding long after the loop ended

The same is true for the current 4-line loop and a half.

while True:
     p = randrange(lo, hi)
     if probable_prime(p):
         break  # p used somewhere else

> Indeed, for those reasons it wasn't "an obvious" win to me - or an 
> obvious loss.? So I just moved on.
> However, after staring at hundreds of other cases, it does strike me as 
> "a small win" today - my brain cells have rewired to recognize more ":=" 
> patterns at a glance.
> Whether that's a good thing or not I don't know, but it is a real thing ;-)

I must admit that I too am already more comfortable with := now than I 
was originally.

Terry Jan Reedy