[Python-Dev] (name := expression) doesn't fit the narrative of PEP 20

Steven D'Aprano steve at pearwood.info
Thu Apr 26 08:09:57 EDT 2018


On Thu, Apr 26, 2018 at 10:17:34AM +0200, Antoine Pitrou wrote:

> I also wonder how long it will be before someone writes:
> 
>     def f(arg):
>         global _lazy_value
>         if predicate(arg) and (_lazy_value := frobnicate()) > arg:
>             ...
> 
> (or something similar with "nonlocal")

What if they did? I don't think that's especially worse than any other 
use of a global, including the current version:

    def f(arg):
        global _lazy_value
        _lazy_value = frobnicate()
        if predicate(arg) and _lazy_value > arg:
            ...


I'm not putting either version forward as paragons of Pythonic code, but 
honestly, they're not so awful that we should reject this PEP because of 
the risk that somebody will do this. People write crappy code and misuse 
features all the time. I cannot count the number of times people write 
list comps just for the side-effects, intentionally throwing away the 
resulting list:

    [alist.sort() for alist in list_of_lists]
    [print(alist) for alist in list_of_lists]

and the honest truth is that when I'm engaged in exploratory coding in 
the REPR, sometimes if I'm feeling lazy I'll do it too. The world goes 
on, and comprehensions are still useful even if people sometimes misuse 
them.



-- 
Steve


More information about the Python-Dev mailing list