# Pythone'er abuses walrus

**URL:** <https://discuss.python.org/t/pythoneer-abuses-walrus/6979>\
**Category:** Python Help\
**Created:** [February 2, 2021, 11:59am UTC](https://discuss.python.org/t/pythoneer-abuses-walrus/6979 "2021-02-02T11:59:12Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [February 2, 2021, 1:40pm UTC](https://discuss.python.org/t/pythoneer-abuses-walrus/6979/2 "2021-02-02T13:40:47Z")

</div>

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!

---

_[View the full topic](https://discuss.python.org/t/pythoneer-abuses-walrus/6979)._
