KOB
KOB

Reputation: 4545

How can I have elements in an Enum evaluate as their value by default?

Is there anyway I can have an Enum like below

class Key(Enum):
    CUSTOMER_ID = 'c_id'
    PHONE_NUMBER = 'phone'

such that calling Key.CUSTOMER_ID evaluates to 'c_id' by default, without the need of calling CUSTOMER_ID.value?

Is there any method I can override that changes what the object returned when evaluated is?

Upvotes: 1

Views: 48

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69021

When you want the Enum members to evaluate as their value, you need to mixin their value type:

class Key(str, Enum):             # note that `str` is before `Enum`
    CUSTOMER_ID = 'c_id'
    PHONE_NUMBER = 'phone'

and in use:

>>> Key.PHONE_NUMBER == 'phone'
True

Upvotes: 1

Related Questions