Skip to content

Instantly share code, notes, and snippets.

@roadsideseb
Last active October 23, 2015 07:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roadsideseb/b3f4e178bcf9957e25a1 to your computer and use it in GitHub Desktop.
Save roadsideseb/b3f4e178bcf9957e25a1 to your computer and use it in GitHub Desktop.
Make the new Enum class in Python 3.4 (backported as 'enum34') have a printable representation
# -*- encoding: utf-8 -*-
from __future__ import print_function
from enum import Enum
class PrintableValue(object):
def __init__(self, value, printable_name):
self.value = value
self.printable_name = printable_name
class EnumWithName(Enum):
def __new__(cls, value):
obj = object.__new__(cls)
obj._value_ = value.value
obj.printable_name = value.printable_name
return obj
class Country(EnumWithName):
AU = PrintableValue('AU', 'Australia')
US = PrintableValue('US', 'United States of America')
CA = PrintableValue('CA', 'Canada')
us = Country('US')
print('Enum name:', us.name)
print('Enum value:', us.value)
print('Printable name:', us.printable_name)
print("US == US:", Country('US') == us)
print("US == CA:", Country('US') == Country('CA'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment