Me not knowing pandas, a general answer:
You can overload anything in python, and they must have done that there. If you define a special method __getitem__
on your class, it is called when you use obj[key]
or obj[start:stop]
(With just key as argument in the former case, with a special slice
object in the latter). You can then return anything you want.
Here's an example to show how __getitem__
works:
class Foo(object):
def __getitem__(self, k):
if isinstance(k, slice):
return k.start + k.stop # properties of the slice object
else:
return k
This gives you:
>>> f = range.Foo()
>>> f[42]
42
>>> f[23:42]
65
I assume that in your example, the __getitem__
method returns some special object, which contains the datetime objects plus a reference to the original ts
object. That special object can then use that information to fetch the desired information later on, when the first_valid_index
method or a similar one is called. (It does not even have to modify the original object, like your question suggested.)
TL;DR: Learn not to worry :-)
Addition: I got curious, so I implemented a minimal example of the behavior you described above myself:
class FilterableList(list):
def __init__(self, *args):
list.__init__(self, *args)
self.filter = FilterProxy(self)
class FilterProxy(object):
def __init__(self, parent):
self.parent = parent
def __getitem__(self, sl):
if isinstance(sl, slice):
return Filter(self.parent, sl)
class Filter(object):
def __init__(self, parent, sl):
self.parent = parent
self.sl = sl
def eval(self):
return [e for e in self.parent if self.sl.start <= e <= self.sl.stop]
>>> l = FilterableList([4,5,6,7])
>>> f = l.filter[6:10]
>>> f.eval()
[6, 7]
>>> l.append(8)
>>> f.eval()
[6, 7, 8]