[Python-ideas] Add a datatype collections.ListView

David Mertz mertz at gnosis.cx
Thu Apr 17 23:22:25 CEST 2014


Using range objects might be worthwhile.  However, your example code,
Terry, won't behave well if you initialize with a generic iterable.  You
need the check for 'hasattr(seq, "__getitem__")' or something equivalent in
the initializer.  But if you have that, you need to make a decision of
*what* concrete sequence to instantiate the iterable as, with list() being
the obvious choice.

E.g. I can do:

  lv = ListView(Thing(random()) for _ in range(100000))

But you can't do:

  sv = SeqView(Thing(random()) for _ in range(100000))

I think, however, there's no reason at all why I should have my .to_list()
method.  That's accomplished more naturally within a special method just as:

  concrete = list(lv[5:10])




On Thu, Apr 17, 2014 at 11:12 AM, Terry Reedy <tjreedy at udel.edu> wrote:

> On 4/17/2014 11:49 AM, David Mertz wrote:
>
>  What I'd really like is a "ListView" that acts something like NumPy's
>> non-copying slices.
>>
>
> Consider a more generic SeqView, especially if you do not intend to mutate
> through the view. I also suggest that you use a range object instead of
> .start, .stop, (and .step). Range gives you a lot for free, including
> slicing.  Untested:
>
> class SeqView:
>     def __init__(self, seq, rng)
>         self.seq = seq
>         self.rng = rng
>
>     def __getitem__(self, index):
>         if isinstance(index, slice):
>             return Seqview(self.seq, self.rng[index])
>         else:
>             return self.seq[self.rng[index]]  # see below
>     def __iter__(self):
>         seq, rng = self.seq, self.rng
>         for i in rng:
>             yield seq[i]
>     ...
>
> >>> r = range(3, 50, 3)
> >>> r[4]
> 15
>
> >>> r[500]
> Traceback (most recent call last):
>   File "<pyshell#2>", line 1, in <module>
>     r[500]
> IndexError: range object index out of range
> # You would want to catch this and change 'range' to SeqView
>
> >>> r[1:3]
> range(6, 12, 3)
> >>> r[slice(1,3)]
> range(6, 12, 3)
> >>> r[slice(1,3,2)]
> range(6, 12, 6)
>
> --
> Terry Jan Reedy
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140417/5740cd78/attachment-0001.html>


More information about the Python-ideas mailing list