Request for comments: python class factory for group of constant values
Question: The following python module is meant to be a basis for "constant" handling in
python. The use case is the following:

  * one groups some constants (basically "names") that belong together with their values into a dictionary
  * with that dictionary bound to class variable a class is created and instantinated run-time
  * the attributes of this class are the constant names, their values are the constants themselves

Code:

    
    
    class ConstantError(Exception):
        def __init__(self, msg):
            self._msg = msg
    
    class Constant(object):
        def __init__(self, name):
            self._name = name
        def __get__(self, instance, owner):
            return owner._content[self._name]
        def __set__(self, instance, value):
            raise ConstantError, 'Illegal use of constant'
    
    def make_const(name, content):
        class temp(object):
            _content = content
            def __init__(self):
                for k in temp._content:
                    setattr(temp, k, Constant(k))
    
        temp.__name__ = name + 'Constant'
        return temp()
    
    num_const = make_const('numeric', {
        'one': 1,
        'two': 2
    })
    
    str_const = make_const('string', {
        'one': '1',
        'two': '2'
    })
    

Use:

    
    
    >>> from const import *
    >>> num_const
    <const.numericConstant object at 0x7f03ca51d5d0>
    >>> str_const
    <const.stringConstant object at 0x7f03ca51d710>
    >>> num_const.one
    1
    >>> str_const.two
    '2'
    >>> str_const.one = 'foo'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "const.py", line 16, in __set__
        raise ConstantError, 'Illegal use of constant'
    const.ConstantError
    >>>
    

Please, comment the design, implementation and correspondence to python coding
guidelines.


Answer: In the same spirit as Kugel, but noticing that
[`collections.namedtuple`](http://docs.python.org/dev/library/collections.html#collections.namedtuple)
is very similar.. it is a tuple, thus immutable, and it has field names.
Namedtuple was introduced in Python 2.6.

Here is how you might use namedtuple:

    
    
    import collections
    
    def make_constants(variables):
        n = collections.namedtuple('Constants', variables.keys())
        return n(**variables)
    
    c = make_constants({"a": 2, "b": 76})
    print c
    # the output is:
    # Constants(a=2, b=76)
    

