On Thu, May 22, 2008 at 11:47 AM, Leif Walsh <adlaiff6@gmail.com> wrote:
On Thu, 22 May 2008, Bruce Leban wrote:
> I think it can better addressed by implementing NamedList and NamedDict:

Oh no...

> NamedList(typename, fieldnames[, optionalfields[, verbose]])
>
> Returns a new list subclass named typename. The new subclass is used to
> create list-like objects that have fields accessible by attribute lookup as
> well as supporting other list operations. Instances of a NamedList may be
> created using a mixture of positional and keyword arguments. If
> optionalfields is not true, then the NamedList must always contain at least
> as many elements as the number of fields. If the NamedDict contains fewer
> elements than the number of fields, missing fields return None when accessed
> by attribute (a.third) and raise IndexError when accessed by index (a[3]).

Is this just a variable-length version of NamedTuple?  It doesn't seem
to offer very much over NamedTuple to me, but I'm open to convincing.

Tuples are immutable. Lists are mutable. The reason I suggest making it variable length is so that it supports the full list semantics and you could for example create a NamedList object with no values and then add values to it (ditto for NamedDict).
 

> NamedDict(typename, fieldnames[, optionalfields[, verbose]])
>
> Returns a new dict subclass named typename. The new subclass is used to
> create dict-like objects that have fields accessible by attribute lookup as
> well as supporting other dict operations. Instances of a NamedDict may be
> created using keyword arguments only. If optionalfields is not true, then
> the NamedDict must have a value for every field. If a NamedDict does not
> contain a field, accessing it returns None when accessed by attribute (a.x)
> and raises KeyError when accessed using by key (a['x']).

This one, though, doesn't sound any different from a struct-style
class, except that it's easier (by ".__dict__") to access the class as
a dictionary.  Hell, here you go:

>>> class NamedDict(object):
>>>   def __getitem__(self, key):
>>>     return self.__dict__[key]

Well, I think the "Named" aspect is important. For example, repr(x) tells you the name. I can tell if two objects are the same type.

Also the NamedDict supports attribute access to the specific fields you've declared and no others. So it's not a freewheeling object that you can add any attribute to it. It's just a lightweight way to create an object backed by a dict (just as NamedTuple is).


--
Cheers,
Leif