A use case for Python assignment expressions

Python 3.8 (2019) added “assignment expressions”, aka the “walrus operator”.

I generally like things that make Python more expression-oriented, like list comprehensions, but I’m ambivalent about these. It’s pretty easy to impair readability by using them overzealously. Is saving one line of code worth making it harder to notice that an assignment is happening?

However, I’ve found a use case I like a lot. I use them in the Django Python shell when doing exploratory ORM queries.

An ORM query as an assignment exprssion returns a result, which gets output immediately for me to inspect; then, if the result is interesting, it’s already assigned to a variable, so I can dive deeper without running the query again.

>>> (ps := Pastebit.objects.filter(syntax="prolog", poster__isnull=False))
<QuerySet [prolog from sam@, prolog from pat@]>

>>> ps[0].poster.email

All of the convenience with none of the maintenance concerns!

Sure, I could do the same thing with an assignment followed by a print, but this is easier to type and has no downside for me.

When it comes to using assignment expressions in production code, I try to at least follow the same rule I use for list comprehensions: Don’t nest them!