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

# 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):

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


I’d give you a hundred hearts if it wasn’t too fawning!

  • That’s an astute observation about where the abuse lies.
  • When tested, your snippet without newlevel works fine; (as do your last two snippets).
  • I learn’t some more with a smile!

Thanks for taking my post in the spirit intended and extending my laugh!

Here’s 99 hearts :hearts: :grinning:

P.S. “…abusing if statement” is a much less comedic title.