Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #5247
| From | Robert Kern <robert.kern@gmail.com> |
|---|---|
| Subject | Re: Slice implementation bug |
| Date | 2011-05-12 12:24 -0500 |
| Organization | The Church of Last Thursday |
| References | <BANLkTikKg0o0zAAmN9miqfr_Dto1qc6hoA@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1480.1305221070.9059.python-list@python.org> (permalink) |
On 5/12/11 6:06 AM, Tambet wrote:
> Hello!
>
> Let's say slice is multidimensional now - how to interpret it?
>
> I excpect these to work:
>
> * m[0, 3] - get one element from matrix
> * m[0:2, 0:2] - get four elements from matrix, iterate over them (I have
> actually an rtree if it doesn't make sense to you)
>
> But it won't, because if m[0, 3] returns something, then m[0:2, 0:2] cannot
> yield anymore.
Let me try to rephrase, since you seem to be leaving out a lot of assumptions.
You are trying to say that you want m[0:2,0:2] to return an iterator and that if
you define __getitem__() such that m[0,3] returns a value, then you cannot
implement __getitem__() to be a generator using a yield statement.
Okay. Fine.
But there is no reason that __getitem__() needs to be a generator function for
you to return an iterator. You can simply return another generator. For example:
def __getitem__(self, key):
if isinstance(key, tuple):
if any(isinstance(x, slice) for x in key):
return self._generate_from_slice(key)
# The default, boring case.
return self._get_value(key)
def _generate_from_slice(self, key):
yield foo
yield bar
yield etc
> Ofcourse I could return an iterator, but this would not be so simple.
Really, it is.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Slice implementation bug Robert Kern <robert.kern@gmail.com> - 2011-05-12 12:24 -0500
csiph-web