[Tutor] is this use or abuse of __getitem__ ?

Steven D'Aprano steve at pearwood.info
Fri Sep 14 17:33:11 CEST 2012

On 14/09/12 22:16, Albert-Jan Roskam wrote:
> 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?

No, that's exactly what __getitem__ is for. It does double-duty for key-lookup
in mappings (dict[key]) and index-lookup in sequences (list[index]).

You can also support ranges of indexes by accepting a slice argument.

Another comment below:

> # 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

Floats? Do you actually have have case number (for example)
0.14285714285714285 ?

For this case, I think it is reasonable to insist on exactly an int,
and nothing else (except possibly a slice object, to support for
example obj[2:15]).


More information about the Tutor mailing list