
Walrus Operator
The Walrus Operator is a new assignment operator announced in Python 3.8 that looks like a walrus.
The walrus operator is used to simplify code when you need an expression while storing the result for future use. This is a common scenario when you need to output the result to a log file.
Example
a = 10
b = 30
if (sum := a + b) > 30:
print(f"The total is {sum}")
Without the walrus operator, you would need to use code similar to this:
a = 10
b = 30
sum = a+b
if (a + b) > 30:
print(f"The total is {sum}")
Like most new features, the walrus operator is only syntactic sugar. Syntactic sugar is when a feature is added to make it easier to express something you could already accomplish using the existing feature set. These changes help make code more readable and manageable.
The walrus operator isn't a game-changer but it does help make code more readable and allows you to accomplish more with fewer lines of code without making code unreadable.
Warning
The walrus operator does require Python 3.8 which not all packages will fully support yet. It may take a couple of days or even weeks for most packages to work out any issues with Python 3.8 so your mileage may vary.
I do recommend running at least Python 3.7.4 in the meantime as there has been numerous security updates. These security updates have been rolled up into 3.6.9 as 3.6 brach is in security fix mode only.
If you haven't seen any of my previous Python series, I highly recommend checking them out below:
My Python Tips Series
- f-strings in Python 3.6
- Underscores in numeric literals
- A better interactive shell
- Secrets Module - New in 3.6
- PEP 8
- Slices
- Named Tuples
- Destructuring
- Counter
- Type Annotation
- Jupyter Notebooks
- Getting Help
- Virtual Environments
- Expiring Dict
- DRY Programming
- Knowing what exists
- Apscheduler
- Caching data with CacheTools
Really like tips. it helped me a lot to start coding.
Great for learning. Easy to follow and progress.
That's neat. I'm stuck on 3.7 at work for now. I see 3.8 also has f'{sum=}' to display a variable name alongside its value. Saves some typing.
I really love the changes in 3.x, I use f-strings so much nowadays. Although lately, I've been messing with JS for a new project.
Hello,
Your post has been manually curated by a @stem.curate curator.
We are dedicated to supporting great content, like yours on the STEMGeeks tribe.
Please join us on discord.
What's your preferred programming language to work with, if you could choose to start any project with one?
I'm currently super into JavaScript, been using it most my life, and it's kinda hard to walk away from lol
Depends on the project, for simple stuff I use Python, but I use Python, JS, C#.
Whatever if we use python for steem assholes like you will flag us and say spam this and that! You suck! Flagged this crap post! oMG! SCAMMER!