On Wed, 25 Apr 2018 18:52:34 -0700 Ćukasz Langa <lukasz@langa.pl> wrote:
On 25 Apr, 2018, at 5:20 PM, Chris Angelico <rosuav@gmail.com> wrote:
On Thu, Apr 26, 2018 at 10:11 AM, Yury Selivanov <yselivanov.ml@gmail.com> wrote:
Just yesterday this snippet was used on python-dev to show how great the new syntax is:
my_func(arg, buffer=(buf := [None]*get_size()), size=len(buf))
To my eye this is an anti-pattern. One line of code was saved, but the other line becomes less readable. The fact that 'buf' can be used after that line means that it will be harder for a reader to trace the origin of the variable, as a top-level "buf = " statement would be more visible.
Making 'buf' more visible is ONLY a virtue if it's going to be used elsewhere. Otherwise, the name 'buf' is an implementation detail of the fact that this function wants both a buffer and a size.
You're claiming that `:=` is nicer in this situation because it's less prominent than regular assignment and thus doesn't suggest that the name stays visible later.
But as others said, `:=` *does* make the name visible later until the enclosing scope ends. In fact, a large part of its appeal is that you can use the result later (as in the `re.search()` example). Will it be visible enough to the reaser in those cases then?
There seems to be a conflict there.
Not only, but seeing `:=` hints that something *special* is going on (some inner expression is being bound to a name). So now we have to be extra careful when reading and reviewing code written that people who like using that syntactical feature. 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") Regards Antoine.