Making the case for "typed" lists/iterators in python

Nathan Rice nathan.alexander.rice at gmail.com
Mon Dec 19 10:56:21 EST 2011


> I think there are two aspects to your idea:
> 1. collections that share a single type
> 2. accessing multiple elements via a common interface

You are correct, and I now regret posing them in a coupled manner.

> Both are things that should be considered and I think both are useful in
> some contexts. The former would provide additional guarantees, for example,
> you could savely look up an attribute of the type only once while iterating
> over the sequence and use it for all elements. Also, I believe you could
> save some storage.
>
> The second aspect would mean that you have a single function call that
> targets multiple objects, which is syntactic sugar, but that's a good thing.
> To some extent, this looks like a C++ valarray, see e.g. [1] and [2] (note
> that I don't trust [1] and that [2] is perhaps a bit outdated), in case you
> know C++ and want to draw some inspiration from this.
>
> Anyway, I believe something like that would already be possible today, which
> would give people something they could actually try out instead of just
> musing about:
>
>   class ValarrayWrapper(object):
>       def __init__(self, elements):
>           self._elements = elements
>       def map(self, function):
>           tmp = [function(x) for x in self._elements]
>           return ValarrayWrapper(tmp)
>       def apply(self, function)
>           self._elements[:] = [function(x) for x in self._elements]
>
> I could even imagine this to implement "generic" attribute lookup by looking
> at the first element. If it contains the according attribute, return a proxy
> that allows calls to member functions or property access, depending on the
> type of the attribute.

Thank you for the references, I am always interested to see how other
languages solve problems.

I have received the "code please" comment repeatedly, I will have to
take some time after work today to deliver.

>> I believe that "typed" lists that get "demoted" to normal lists with
>> a warning on out of type operations preserve this information while
>> providing complete backwards compatibility and freedom.
>
>
> I don't think that a warning helps people write correct code, a meaningful
> error does. Otherwise, with the same argument you could convert a tuple on
> the fly to a list when someone tries to change an element of it.

I do agree errors are more normative than warnings.  The problem with
an error in these circumstances is it will certainly break code
somewhere.  Perhaps a warning that becomes an error at some point in
the future would be the prudent way to go.

Thanks!

Nathan



More information about the Python-list mailing list