Expressive walrus assignment expressions Python 3.8

Timeless
Nov 19, 2020

--

I thought it would be fun to write about Python’s value-or operator (sometimes affectionately known as the “walrus operator”) because it brings a lot of more expressive syntax and what the heck moments

Reuse new value assignment in if condition

It is possible to combine value-or (less preferable called walrus) operator with and or or expression which illustrated in this example

This works because ok := len(a) evaluates as a True so it’s possible to stack more expressions after `and` operator.

Likewise you can create even more complex expressions with reference to size

Deriving Let operator prototype

Now let’s try to tweak this further to make these expressions more understandable. We can use let() placeholder function which always returns and evaluates as True. The key feature here that we can embed the walrus operator in the argument of a function call.

Extending the previous example further to multiple variables

Even though I would think twice before using these features it’s been fun to twist this syntax just to explore

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response