I’ve got a variable that can hold one of two values. This simple logic reverses it:
opt_in_status = some_method_that_returns_an_opt_in_status()
# switch the opt_in_status
opt_in_status = "opted_in" if opt_in_status == "unsubscribed" else "unsubscribed"
I don’t like the fact that I’ve hardcoded the magic string unsubscribed twice. I could put that into another variable
opt_in_status = some_method_that_returns_an_opt_in_status()
# switch the opt_in_status
magic_string = "unsubscribed"
opt_in_status = "opted_in" if opt_in_status == magic_string else magic_string
but is there a more concise one-liner that will do this for me?
I’m using python 3.9
>Solution :
From python 3.8 you can use the walrus operator :=
opt_in_status = "opted_in" if opt_in_status == (magic_string := "unsubscribed") else magic_string