Expressive walrus assignment expressions Python 3.8

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 or expression which illustrated in this example

Image for post
Image for post

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

Image for post
Image for post

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.

Image for post
Image for post

Extending the previous example further to multiple variables

Image for post
Image for post

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store