[Tutor] is this use or abuse of __getitem__ ?

Albert-Jan Roskam fomcl at yahoo.com
Fri Sep 14 14:16:49 CEST 2012


Hi,

I defined a __getitem__ special method in a class that reads a binary data file using a C library. The docstring should clarify
the purpose of the method. This works exactly as I intended it, however, the "key" argument is actually used as an index
(it also raises an IndexError when <key> is greater than the number of records in the file). Am I abusing the __getitem__ method, or is this just a creative way of using it?


# Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32

    def __getitem__(self, key):
        """ This function reports the record of case number <key>.
        For example: firstRecord = FileReader(fileName)[0] """
        if not isinstance(key, (int, float)):
            raise TypeError
        if abs(key) > self.nCases:
            raise IndexError
        retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(int(key)))
        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]" % \
                  (key, retcodes[retcode1], retcodes[retcode2])
        return record
 
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list