[Python-ideas] namedlist() or Record type

Steven D'Aprano steve at pearwood.info
Wed Jul 24 14:54:07 CEST 2013


On 24/07/13 17:50, anatoly techtonik wrote:
> Rationale: There are many 2D data with table layout where order is
> important and it is hard to work with them in Python.
[...]

It sounds to me that what you want is a mutable namedtuple. At least, that's what I often want. namedtuple was a fantastically useful addition to the standard library, I think a mutable record type would be too.

Here's a quick and dirty (emphasis on the dirty) proof of concept of the sort of thing I'd like:

def record(name, fields):
     def __init__(self, *args):
         for slot, arg in zip(self.__slots__, args):
             setattr(self, slot, arg)
     return type(name, (),
            {'__slots__': fields.split(), '__init__': __init__}
                 )


I don't put this forward as a production-ready solution, it is missing a nice repr, and doesn't support indexing or sequence unpacking, and I'm not really sure if it should use slots, but it gives the idea of the sort of thing that can be done.


[...]
> I hacked OrderedDict to accept list as param and allow attribute
> access. It doesn't behave as named list - you still need to call
> .values() to get list back, and indexed access doesn't work as well.
>
> http://bugs.python.org/file31026/DictRecord.py


I don't think that OrderedDict is a good base class for this. Dicts have lots of methods that are completely inappropriate for a record/struct-like object.



-- 
Steven


More information about the Python-ideas mailing list