marlon
marlon

Reputation: 7703

Is there a better way to represent enum with same values?

class FuzzyTime(Enum):
    morning = 1
    dawn = 2
    noon = 3
    midday = 4
    afternoon = 5
    evening = 6
    sunset = 7
    dusk = 8
    night = 9

In those cases, I want to represent morning & dawn, noon & midday, evenning, sunset, dusk & night as synonyms. So ideally, I want something like:

class FuzzyTime(Enum):
        morning, dawn = 1
        noon, midday = 2
        afternoon = 3
        evening, sunset, dusk, night  = 6
        

When I use it, I want to do something like:

if MORNING == FuzzyTime.morning:
       pause

This can match both 'morning' & 'dawn'. Is that possible?

EDIT: When I use it, I want to compare whether a string matches one of the values. Let's say my string is:

 s = 'morning'
 if s == FuzzyTime.morning or s == FuzzyTime.dawn:
     return get_morning_time(reference_time)

I just want to know whether there a way to avoid writing 'if s == or s ==' statement. I want to get rid of the 'or' in the if statement, if possible, but achieve the same effect.

Upvotes: 0

Views: 182

Answers (3)

Prune
Prune

Reputation: 77880

I don't see why you're using enumeration values for this. You're already having troubles to translate between a string and an enumeration label. Just define your sets of terms:

class FuzzyTime():
    MORNING = {"morning", "dawn"}
    MIDDAY = {"noon", "midday"}
    AFTERNOON = {"afternoon"}
    NIGHT ={"evening", "sunset", "dusk", "night"}

From here, simply use the "natural" Python operator in

for s in ["dawn", "noon", "dusk"]:
    if s in FuzzyTime.MORNING:
        print("I need caffeine.")
    elif s in FuzzyTime.MIDDAY:
        print("I'm ready to solve the world's problems!")

... etc.

Output:

I need caffeine.
I'm ready to solve the world's problems!

Does that make it easy enough for you to use?

Upvotes: 2

itismoej
itismoej

Reputation: 1847

You mean something like this?

class FuzzyTime(Enum):
    morning = dawn = 1
    noon = midday = 2
    afternoon = 3
    evening = sunset = dusk = night  = 6

UPDATE:

Use in operator:

class FuzzyTime:
    morning = 'morning'
    dawn = 'dawn'
    noon = 'noon'
    midday = 'midday'
    afternoon = 'afternoon'
    evening = 'evening'
    sunset = 'sunset'
    dusk = 'dusk'
    night = 'night'

    m_d = [morning, dawn]
    n_m = [noon, midday]
    e_s_d_n = [evening, sunset, dusk, night]
s = 'morning'
if s in FuzzyTime.m_d:
    return get_morning_time(reference_time)

Upvotes: 1

Stephen Quan
Stephen Quan

Reputation: 26214

Your requirements are a bit weird, but, how about a dictionary, e.g.

obj = {
    'morning': 1,
    'dawn': 1,
    'noon': 2,
    'midday': 2,
    'afternoon': 3,
    'evening': 6,
    'sunset': 6,
    'dusk': 6,
    'night': 6
}

Then, you can 'morning' with an input string, e.g.

str = 'dawn'
is_morning = obj[str] == obj['morning']

Upvotes: 1

Related Questions