[Tutor] is this use or abuse of __getitem__ ?

Albert-Jan Roskam fomcl at yahoo.com
Mon Sep 17 09:42:41 CEST 2012


<snip>

> 
> http://code.google.com/p/psutil
> 


I looked at the website and it looks like a cool module. Some of it appeared to be *nix only, but I'll have to dig into it more.
But it's also just like you said: how far should one go with micromanaging things?  Maybe some things are the caller's responsibility.


> If you're also supporting the iterator protocol with the __iter__
> method, then I think a helper _items(start, stop, step) generator
> function would be a good idea.
> 
> Here's an updated example (not tested however; it's just a suggestion):
> 
> 
>     import operator
> 
>     def _items(self, start=0, stop=None, step=1):
>         if stop is None:
>             stop = self.nCases
> 
>         for i in range(start, stop, step):
>             retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(i))
>             self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer()
>             retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr)
>             record = struct.unpack(self.structFmt, self.caseBuffer.raw)
>             if any([retcode1, retcode2]):
>                 raise RuntimeError("Error retrieving record %d [%s, 
> %s]" %
>                     (i, retcodes[retcode1], retcodes[retcode2]))
>             yield record
> 
> 
>     def __iter__(self):
>         return self._items()
> 
> 
>     def __getitem__(self, key):
> 
>         is_slice = isinstance(key, slice)
> 
>         if is_slice:
>             start, stop, step = key.indices(self.nCases)
>         else:
>             key = operator.index(key)
>             start = key + self.nCases if key < 0 else key
>             if not 0 <= start < self.nCases:
>                 raise IndexError
>             stop = start + 1
>             step = 1
> 
>         records = self._items(start, stop, step)
>         if is_slice:
>             return list(records)
>         return next(records)
> 
> 

Awesome, thank you so much. This has been very inspiring! When this is working, I'm thinking about also implementing an Ellipsis (just because it's possible ;-), so I can cut out certain parts of the data using a numpy array. Another idea would be to also use __getitem__ as a dictionary. So when the data contains an id (let's say ssn), r = Reader(key="ssn"); r.data["87654321"] returns the corresponding (first available) record. But although this is cool from an educational perspective, I do wonder whether, from a design perspective, it's a good idea to make __getitem__ this fully packed.


<snip>



More information about the Tutor mailing list