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
--
http://mail.python.org/mailman/listinfo/python-list