[Python-Dev] from tuples to immutable dicts

Martin v. Loewis martin@v.loewis.de
23 Nov 2002 12:19:05 +0100

Armin Rigo <arigo@tunes.org> writes:

> Here is a related suggestion: enhancing or subclassing tuples to
> allow items to be named. Example
> syntax:
>     (1,2,c=3,d=4)
> would build the 4-tuple (1,2,3,4) with names on the last two items.

While I agree on the need for a struct-like type, I'm strongly opposed
to adding new syntax, or even make it a builtin type (i.e. one that is
referenced from __builtins__).

Provide such a type using the standard language mechanisms.

> I believe that it fills a hole between very small structures
> (e.g. (x,y) coordinates for points) and large structures naturally
> implemented as classes: it allows small structures to grow a bit
> without turning into an obscure 5- or 10-tuple. As a typical
> example, consider the os.stat() trick: it currently returns an
> object that behaves like a 10-tuple, but whose items can also be
> read via attributes for the sake of clarity.

I think the structseq type is a good starting point.

Fred once had a plan to expose structseqs to Python, to allow the
creation of new structs in Python. I was suggesting that there should
be a method new.struct_seq, which is called as

struct_seq(name, doc, n_in_sequence, (fields))

where fields is a list of (name,doc) tuples. The resulting thing would
be similar to os.stat_result: you need to call it with the mandatory
fields in sequence, and can call it with the optional fields by
keyword argument.

> * use 'tuple' or a new subtype 'namedtuple' or 'structure'?

No new builtins at all, please.

> * the suggested syntax emphasis the use of strings for the keys, but
> the constructor could be more general, taking arbitrary hashable
> values:


> * how do we read the key names? 

You can currently get them from the type's __dict__, although this
contains more information than you want.

However, what do you need the key names for?

> * shoud name collisions be allowed inside a namedtuple?

You mean, two fields with the same name? No.

> * what about * and ** call syntaxes? 

Irrelevant, since syntax extensions are not acceptable.

> * dissymetries between namedtuples and dicts: operations like 'in'
> and iteration operates on values in tuples, but on keys in dicts...

A struct really is a sequence, not a mapping.