Skip to content

Instantly share code, notes, and snippets.

@Jamim
Last active April 6, 2018 14:54
Show Gist options
  • Save Jamim/5c794c148a301d20c5314b1e1ab2c1f8 to your computer and use it in GitHub Desktop.
Save Jamim/5c794c148a301d20c5314b1e1ab2c1f8 to your computer and use it in GitHub Desktop.
Labeled enum for Python 3.4+ (tested with Python 3.6)
from enum import Enum
class LabeledEnum(Enum):
@staticmethod
def __new_member__(cls, value, label):
enum_member = object.__new__(cls)
enum_member._value_ = value
enum_member.label = label
return enum_member
@classmethod
def get_choices(cls):
return tuple((member.value, member.label) for member in cls)
@Jamim
Copy link
Author

Jamim commented Apr 6, 2018

Usage example:

from labeled_enum import LabeledEnum


class Example(LabeledEnum):
    """
    >>> Example(1)
    <Example.ONE: 1>
    >>> Example(1).label
    'First value'
    >>> Example.ONE.value
    1
    >>> Example.ONE.label
    'First value'
    >>> Example(2)
    <Example.TWO: 2>
    >>> Example(2).label
    'Second value'
    >>> Example.TWO.value
    2
    >>> Example.TWO.label
    'Second value'
    >>> Example.get_choices()
    ((1, 'First value'), (2, 'Second value'))
    """

    ONE = 1, 'First value'
    TWO = 2, 'Second value'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment