Skip to content

Instantly share code, notes, and snippets.

@glenfant
Last active November 11, 2021 14:08
Show Gist options
  • Save glenfant/7335823 to your computer and use it in GitHub Desktop.
Save glenfant/7335823 to your computer and use it in GitHub Desktop.
There is no enumeration type in Python a in some other languages as pascal or RubyThis is a poor man's enumeration that works as expected.
# -*- coding: utf-8 -*-
"""Python enumeration"""
import itertools
def enumeration(name, *auto, **named):
"""Pythonic enumeration type
>>> Colors = enumeration('Colors', 'GREEN', 'RED', 'YELLOW')
>>> Colors.GREEN, Colors.RED, Colors.YELLOW
(0, 1, 2)
>>> Status = enumeration('Status', 'UNKNOWN', TRUE=True, FALSE=False)
>>> Status.TRUE, Status.FALSE, Status.UNKNOWN
(True, False, 0)
"""
values = dict(itertools.izip(auto, xrange(len(auto))), **named)
return type(name, (), values)
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