Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One-liner to conditionally swap a value

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading