Welcome, guest | Sign In | My Account | Store | Cart

Recipe for Python Enum class that builds on the "FOO = 1" pattern by adding a printable name.

In other words, an Enum instance is a named integer.

Python, 38 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""Enumeration class representing a named integer."""


class Enum(int):
    """Enumeration value is a named integer."""
    #pylint: disable=R0904

    def __new__(cls, rank, name):
        obj = int.__new__(cls, rank)
        obj.name = name
        return obj

    def __repr__(self):
        return 'Enum(' + repr(int(self)) + ', ' + repr(self.name) + ')'

    @staticmethod
    def lookup(enumvals):
        """Lookup from int/string to Enum instance for provided values"""
        result = {int(v): v for v in enumvals}
        result.update({v.name: v for v in enumvals})
        return result


def test():
    """Tests of the Enum class"""
    # pylint: disable=C0103
    WEAK = Enum(1, 'WEAK')
    MODERATE = Enum(2, 'MODERATE')
    STRONG = Enum(3, 'STRONG')
    assert repr(STRONG) == "Enum(3, 'STRONG')"
    assert WEAK < MODERATE < STRONG
    assert MODERATE > WEAK
    assert WEAK.name == 'WEAK'
    assert WEAK == 1
    assert WEAK < 3

if __name__ == '__main__':
    test()

Useful if all you want from your Enum values is to have them come with a readable name, whether for display or debugging purposes.

Features:

  1. Enum is just an int, with a name attached.
  2. Explicit declaration just like stdlib (logging.DEBUG, re.MULTILINE)
Created by Graham Poulter on Tue, 25 Oct 2011 (MIT)
Python recipes (4591)
Graham Poulter's recipes (7)

Required Modules

  • (none specified)

Other Information and Tasks