[Python-ideas] Adding "Typed" collections/iterators to Python

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Dec 19 07:48:32 CET 2011

Nick Coghlan wrote:

> What you seem to be asking for is a general purpose typed container
> factory along the following lines:
>     def typed_container(container_type, data_type):
>         class TypedContainer(container_type):
>             def __getattr__(self, attr):
>                 data_type_attr = getattribute(data_type, attr)
>                 if callable(data_type_attr):
>                     _result_type = type(self)
>                     def _broadcast(*args, **kwds):
>                         _result_type(data_type_attr(x, *args, **kwds) for x in self)
>                     return _broadcast
>                 return data_type_attr
>         return TypedContainer

Seems to me this would be better described as a "broadcasting container"
than a "typed container". The only use it makes of the element type is
to speed things up a bit by extracting bound methods. So the typed-ness
is not an essential feature of its functionality, just something
required to support an optimisation.

Extended to handle the various operator methods, this might be a useful
thing to have around. In conjunction with array.array, it could provide
a kind of "numpy lite" for when depending on full-blown numpy would seem
like overkill.


More information about the Python-ideas mailing list