Home > front end >  What is the best way to allow string to be one of two constant values? [duplicate]
What is the best way to allow string to be one of two constant values? [duplicate]

Time:09-17

Let's say, I have the following code:

class SomeChoices(object):
    CHOICE_A = "Sub"
    CHOICE_B = "First Team"

    @classmethod
    def choices(cls):
        return cls.CHOICE_A, cls.CHOICE_B

The comparing string for CHOICE_B can be both First Team or First-Team. What is the best practice to compare them so that both First Team and First-Team would be considered as CHOICE_B?

CodePudding user response:

s in {'First Team', 'First-Team'}

This checks if the string exists in the set efficiently.

CodePudding user response:

It's a matter of preference. If this is just a static check that you know you won't expand on, you can just implement something quick like bwdm's answer.

If you want to make it expandable, so that you can dynamically add more words to compare with, you're best off keeping multiple sets, each containing viable words.

class SomeChoices(object):
    choices = {
        "A":{"Sub"}, "B":{"First Team", "First-Team"}
    }

Now you can easily check if something is part of a choice, and also expand it if you want.

"First-Team" in SomeChoices.choices["B"]    # True
"First Team" in SomeChoices.choices["B"]    # True
"First_Team" in SomeChoices.choices["B"]    # False

SomeChoices.choices["B"].add("First_Team")
"First_Team" in SomeChoices.choices["B"]    # True

SomeChoises.choices["C"] = {"Second Team"}
"Second Team" in SomeChoices.choices["C"]   # True

This follows the open/close principle, where a module is easy to expand upon without needing to change the code for it.

  • Related