Last active
November 11, 2021 14:08
-
-
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.
This file contains hidden or 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
# -*- 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