[Python-Dev] from tuples to immutable dicts

Armin Rigo arigo@tunes.org
Sun, 24 Nov 2002 06:05:34 -0800 (PST)

On Sun, Nov 24, 2002 at 09:15:58AM +0100, Martin v. Loewis wrote:
> > > 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

This goes against the initial proposal, which was to have a lightweight and declaration-less way to
build structures. When you feel a need to explicitely declare the type of a structure, then making it
a class is just the way to go. I'm thinking about no-type small structures, the ones for which you'd
almost use dictionaries:

   point = {'x': 5, 'y': 6}
   print point['x']
   print point['y']

which looks reasonably if not quite entierely nice. The problem is that it is incompatible with
tuples: you cannot smoothly go from tuples to dicts without changing your whole program.

What about just allowing keyword parameters in 'tuple'?

   point = tuple(5, 6, color=RED, visible=False)

As the order of the keyword parameters is lost, they cannot show up positionally (i.e. the length of
the above tuple is 2). But this might be exactly what you want in some cases. The above tuple behaves
like (5,6) in many situations. If desired you can store the values both positionally and as attributes
-- since it's immutable, it doesn't matter beyond a slight duplication in the constructor:

   x = ...
   y = ...
   point = tuple(x, y, x=x, y=y)
   assert point[0] == point.x == x
   assert point[1] == point.y == y

In this solution, 'point.__dict__' would return a read-only dict wrapper similar to '<type>.__dict__'.

For an efficient C implementation, 'tuple-with-attributes' should be a subtype of 'tuple', and not
'tuple' itself, to avoid 'sizeof(PyObject*)' extra bytes in all the tuples of the program. There is no
need for the new type name to show up in __builtins__.