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

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.