jamiet
jamiet

Reputation: 12264

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?

I'm using python 3.9

Upvotes: 0

Views: 79

Answers (2)

matszwecja
matszwecja

Reputation: 8005

Probably outside the scope of the question, but I think this use-case really asks for using enum values.

from enum import Enum

class OptInStatus(Enum):
    UNSUBSCRIBED = False
    OPTED_IN = True

optInStatus = OptInStatus(False)
print(optInStatus.name)    #UNSUBSCRIBED

optInStatus = OptInStatus(not optInStatus.value)    # Here is where the swap happens
print(optInStatus.name)    #OPTED_IN

This way reverse operation is much shorter, clearer in its effects and there are no magic strings involved at all. Of course, this would require interface change or conversion from string return values like so:

    @classmethod
    def fromString(cls, string):
        if string == "unsubscribed":
            return cls.UNSUBSCRIBED
        elif string == "opted_in":
            return cls.OPTED_IN

optInStatus = OptInStatus.fromString("unsubscribed")

Upvotes: 0

Deusy94
Deusy94

Reputation: 757

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

Upvotes: 1

Related Questions