Last active
October 23, 2015 07:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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