possible attribute-oriented class

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 5 06:49:00 CEST 2009


On Fri, 04 Sep 2009 22:37:15 +0200, Jan Kaliszewski wrote:

> Named tuples (which indeed are really very nice) are read-only, but the
> approach they represent could (and IMHO should) be extended to some kind
> of mutable objects.

What do you mean "read-only"? Do you mean immutable?

What sort of extensions did you have in mind? You can add arbitrary 
attributes to a named tuple by subclassing:

>>> class Cls(namedtuple('C', 'x y z')):
...     pass
...
>>> inst = Cls(1, 2, 3)
>>> inst.foo = 4


It's hard to see how you could have a named list... how would it work? If 
you append data to the namedlist, what names would they get? If you sort 
the namedlist, do the names move, or just the data?



> The old discussion, the above link points to, shows that such a
> dot-accessible dict-like class is something that many people need and
> repeatedly implemet it (more or less perfectly) for themselves.

I think it's something which people copy from other languages because 
that's what they're used to, not because they need it.

It's just a change in syntax. Whether you write x.key or x['key'] is a 
matter of convenience. Attribute access is optimized for when you know 
the key names at compile time, key access is optimized for when you don't 
know the names until runtime. Compare:

# You know the key when you write the code.
x.key versus x['key']

# You don't know the key until runtime.
s = get_key()
getattr(x, s) versus x[s]



-- 
Steven



More information about the Python-list mailing list