[Python-Dev] RE: iterable slices

Alex Martelli aleax@aleax.it
Thu, 2 May 2002 09:20:52 +0200


On Thursday 02 May 2002 09:05, Damien Morton wrote:
	...
> I hadnt thought of that, but its kind of elegant.
>
> for i in (a:b:c:d:e):
>
> Would probably be an error. Trying to make an iterator out of anything
> but a 2 or 3 element slice should fail, unless you supply your own
> iterator factory.

Currently you can't "supply your own factory" between iter() and a given
object type -- iter() looks for the object's __iter__ (&c), not in any 
registry of adapter-factories.  PEP 246 might be tweaked to change
that, but it would be a doubtful change IMHO.


> Omitted slice elements being None is a nice idea, and would work with
> the RDF notation
>
> (subj::obj) -> slice(subj, None, obj)
>
> It gets a little hairy when you start doing things like this, however
>
> (::) -> slice(None, None, None)

You could forbid it:

>>> slice()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: slice() takes at least 1 argument (0 given)

> And what then of the 1-element slice? (if its necessary at all)

It definitely is (to indicate "all items from i" or "all items up to i",
depending on which 'element' you mean, start or stop).

> (1:) -> slice(1, None) or slice(1)??

>>> slice(3)
slice(None, 3, None)
>>>

i.e., like (:3).  (1:) must clearly mean "all from 1 upwards" by
analogy with sequence slicing such as somelist[1:].


Alex