4 ms·
In that example I gave, I totally agree with you. One area where I find walrus operators kinda useful is with dealing with iterators. For example, ''' iterabl
by edwardjxli 1y ago
In that example I gave, I totally agree with you. One area where I find walrus operators kinda useful is with dealing with iterators. For example,
'''
iterable = iter(thing)
while val := next(iterable, None):
print(val)
'''
is a lot cleaner in my opinion compared to
'''
iterable = iter(thing)
val = next(iterable, None)
while val is not None:
print(val)
val = next(iterable, None)
'''
Reason why I did not use this example outright was because I wasn't sure if people were familiar with the iter api, so I just chose a simpler example for the blog.
- maleldil 1y agoIsn't this equivalent to just `for val in thing`?
- sgarland 1y agoIf `thing` already supports iteration, then yes, but sometimes you need to build your own [0]. [0]: https://docs.python.org/3/library/functions.html#iter https://docs.python.org/3/library/functions.html#iter
- maleldil 1y agoParent's example had a direct `iter(thing)`. Even if you had to use `iter(thing, sentinel)`, you'd still use `for val in iter(thing, sentinel)`, not while.
- pansa2 1y agoYeah, I think the walrus operator is occasionally useful in `while` statements, but that's about it. IMO it wasn't worth the additional language complexity for an operator that's so rarely useful.
- Izkata 1y agoYou can get code formatting by indenting with 2 spaces: https://news.ycombinator.com/formatdoc https://news.ycombinator.com/formatdoc