I am working on a rudimentary Breakout clone, and I was doing the wall collision. I have a function that I initially treated as a Boolean, but I changed it to return a different value depending on which wall the ball hit. I used the walrus operator to capture this value while still treating the function like a bool. I probably could have just defined a variable as the function’s return value, then used it in an if statement. But it felt good to use this new thing I’d only heard about, and didn’t really understand what it did. I was honestly kind of surprised when it actually worked like I was expecting it to! Pretty cool.

-12 points
Removed by mod
permalink
report
reply
12 points

My most common use case is probably looking up stuff that may or may not be in a dict.

if (val := dct.get(key)) is not None:
    # do stuff with val

I guess that’s pretty similar to what you were doing?

Sometimes I also use it in some crazy list comprehension thing when I get backed into a corner, though it’s hard to think of an example off the top of my head? It usually happens when I’m in a rush and desperate to get something working, but it has an uncanny way of being just the thing you need at that point.

permalink
report
reply
3 points

Relatively new to Python so that’s news to me.

Other languages I’ve used support assignment like that but I always avoid it, but they just used = so I’ll give this walrus a try and see if the different syntax makes it any better in my mind

permalink
report
reply

Python

!python@programming.dev

Create post

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events
Past

November 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
  • Pythörhead: a Python library for interacting with Lemmy
  • Plemmy: a Python package for accessing the Lemmy API
  • pylemmy pylemmy enables simple access to Lemmy’s API with Python
  • mastodon.py, a Python wrapper for the Mastodon API
Feeds

Community stats

  • 804

    Monthly active users

  • 467

    Posts

  • 2.4K

    Comments