assign the condition of the if statement to a variable

Question:

I have a long snippet of code and i am trying to shorten it.
This is what I have now:

statuses = cleaned_data.get("statuses")
if statuses:
    for status in statuses:
        ...

it would be nice if i can assign the value of cleaned_data.get("statuses") inside the if condition, like this:
if cleaned_data.get("statuses") as statuses
and carry on.
Is it doable in python?

Asked By: Ahmad Hussian

||

Answers:

You can use Assignment Expression (a.k.a walrus operator):

if statuses := cleaned_data.get("statuses"):
    for status in statuses:
Answered By: matszwecja
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.