Best way to enumerate something in python

Hallvard B Furuseth h.b.furuseth at usit.uio.no
Wed May 26 13:40:11 EDT 2004


David Stockwell wrote:

> I have a list of columnames for a db and I decided to put them in a giant 
> tuple list for two reasons:
>    1) its unchangeable
>    2) I was hoping that creating an enumeration of those names would be easy
> 
> (...)
>
> I would like to create an enumeration with 'friendly names' that map to the 
> particular offset in my column name tuple.

Like this?

>>> class tuple_names(tuple):
...     def __init__(self, dummy = None):
...         self.__dict__ = dict(zip(self, range(0, len(self))))
... 
>>> x = tuple_names(('a', 'b', 'c'))
>>> x
('a', 'b', 'c')
>>> x.c
2


Another approach to enumeration which I've just been playing with:

import sys

class Named_int(int):
    """Named_int('name', value) is an int with str() = repr() = 'name'."""
    def __new__(cls, name, val):
        self = int.__new__(cls, val)
        self.name = name
        return self
    def __str__(self): return self.name
    __repr__ = __str__
    __slots__ = 'name'

def Enum_dict(_Enum_dest = None, **src):
    if _Enum_dest is None:
        _Enum_dest = {}
    for name, val in src.items():
        _Enum_dest[name] = Named_int(name, val)
    return _Enum_dest

def Enum(**mapping):
    """Enum(var = integer, ...) defines the specified named integer variables.
    Each variable is set to a Named_int with name 'var' and value 'integer'.
    Enum() only works in class bodies and at file level, not in functions."""

    Enum_dict(sys._getframe(1).f_locals, **mapping)

# Test
if __name__ == '__main__':
    x = Named_int('y', 3)
    print x, str(x), int(x), "(%s = %d)" % (x, x)

    Enum(
        debug = 0,
        info = 1,
        warning = 2,
        error = 3,
        critical = 4
        )
    print"%s = %d" % (info, info)

    class foo: Enum (one = 1, two = 2)
    print foo.two

    print Enum_dict(three = 3, five = 5)
    print Enum_dict({None: ()}, seven = 7)

-- 
Hallvard



More information about the Python-list mailing list