[Python-ideas] namedlist() or Record type

anatoly techtonik techtonik at gmail.com
Fri Jul 26 12:48:49 CEST 2013


On Wed, Jul 24, 2013 at 3:54 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> 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.

Indexing is vital for lists, the idea is to have a list replacement,
just with convenient names to write more readable code. Slots looks
like a good solution to throw errors about typos in attribute names as
early as possible.

> [...]
>
>> 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.

I agree, but it was the only way I can think of to get clean
definition for list fields, such as:

class TermiosState(DictRecord):
    NAMES = ['iflag', 'oflag', 'cflag', 'lflag', 'ispeed', 'ospeed', 'cc']

This definition can be easily parsed by static analyzer tools like
pyflakes. The standard nametuple definition is not so clear to them:

Point = namedtuple('Point', ['x', 'y'], verbose=True)

--
anatoly t.


More information about the Python-ideas mailing list