Pythone'er abuses walrus

It’s not the walrus operator that is being abused, it’s the if
operator. You have:

None if stack[-1].append(innermost:=[]) else innermost

That use of the walrus operator is perfectly fine! All you are doing is
using the walrus as a way to keep a named reference to an expression you
have just used, which is exactly what the operator was invented for!

(This example is a little unusual only in that the expression being
captured is so simple, a plain old literal [], instead of something
complicated or expensive.)

There are other ways to get the same effect. Who needs a named
reference?

# Untested.
if this > len(stack):
    stack[-1].append([])         # nest the new level
    stack.append(stack[-1][-1])  # and push it

Anyway, the walrus is fine. It’s the if operator that is freaky:

something that never gets used
if something that always return False
else something

So let’s fix it!

if this > len(stack):
    stack[-1].append(newlevel:=[])
    stack.append(newlevel)

People who don’t like the walrus operator would prefer to put
newlevel = [] in its own statement, and honestly I agree that is
probably better. But using the walrus operator to re-use the same list
is pretty good.

We can even save another line, without using a semicolon:

if this > len(stack):
    stack[-1].append(newlevel:=[]) or stack.append(newlevel)

Pretty hackish, but it’s still better than the abuse of the ternary if
operator!

3 Likes