Skip to content

Instantly share code, notes, and snippets.

@hanks
Last active August 29, 2015 14:01
Show Gist options
  • Save hanks/893d65782c02a129c4f0 to your computer and use it in GitHub Desktop.
Save hanks/893d65782c02a129c4f0 to your computer and use it in GitHub Desktop.
python enum
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Enum(object):
"""Enum simulation class with auto increment id
>>> a = Enum(['type_1', 'type_2', 'type_3'])
>>> a.type_1
1
>>> a['type_1']
1
>>> print len(a)
3
>>> print a
[('type_1', 1), ('type_2', 2), ('type_3', 3)]
>>> 1 in a
True
>>> 4 in a
False
>>> 'type_1' in a
False
>>> a.append('type_4')
"""
START_INDEX = 1
def __init__(self, aList):
assert(type(aList) == type([]))
self.__aList = aList
def __len__(self):
return len(self.__aList)
def __getattr__(self, item):
if item in self.__aList:
return self.START_INDEX + self.__aList.index(item)
raise KeyError
def __getitem__(self, item):
return self.__getattr__(item)
def __str__(self):
return str([(item, self.__getattr__(item)) for item in self.__aList])
def append(self, item):
self.__aList.append(item)
def __iter__(self):
return iter([self.__getattr__(item) for item in self.__aList])
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment