[Python-Dev] from tuples to immutable dicts

Martin v. Loewis martin@v.loewis.de
24 Nov 2002 18:10:54 +0100


Armin Rigo <arigo@tunes.org> writes:

> This goes against the initial proposal, which was to have a
> lightweight and declaration-less way to build structures.

Yes. I never had the need for a lightweight and declaration-less way
to build structures. What is the need?

>    point = {'x': 5, 'y': 6}
>    print point['x']
>    print point['y']
> 
> which looks reasonably if not quite entierely nice. 

If looking reasonable, or even nice, is the goal, why not write

class Point:
  def __init__(self, x, y):
    self.x, self.y = x, y

point = Point(5, 6)
#or
point = Point(x=5, x=6)

print point.x
print point.y


> The problem is that it is incompatible with tuples: you cannot
> smoothly go from tuples to dicts without changing your whole
> program.

So you need to enhance class Point

  def __getitem__(self, index):
    if index == 0:return self.x
    if index == 1:return self.y
    raise IndexError

> What about just allowing keyword parameters in 'tuple'?
> 
>    point = tuple(5, 6, color=RED, visible=False)

I have to problems imagining such an extension:

1. I'm not sure this would be useful.
2. I can't imagine how to implement it, without compromising performance
   for tuples.
3. It can be easily implemented without any change to builtin types:

class Tuple(tuple):
    pass

def TUPLE(*args, **kw):
    res = Tuple(args)
    res.__dict__=kw
    return res

point = TUPLE(5, 6, color="RED", visible=False)
print point[0]
print point.color

Regards,
Martin