classification
Title: Overridden __getitem__ not called on use of slice syntax when inheriting from tuple
Type: behavior Stage: resolved
Components: Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: jpthalman, serhiy.storchaka, steven.daprano
Priority: normal Keywords:

Created on 2018-04-21 06:47 by jpthalman, last changed 2018-04-21 07:23 by serhiy.storchaka. This issue is now closed.

Messages (3)
msg315551 - (view) Author: Jacob Thalman (jpthalman) Date: 2018-04-21 06:47
class MyTuple(tuple):
    def __getitem__(self, item):
        print "Getting {}".format(item)

t = MyTuple((1, 2))
t[0] -> "Getting 0"
t[1] -> "Getting 1"
t[slice(None)] -> "Getting slice(None, None, None)"
t[:] -> (1, 2)
t[slice(None, 1)] -> "Getting slice(None, 1, None)"
t[:1] -> (1,)

Overriding __getattribute__ confirms that the overridden __getitem__ is never called when syntactic slice syntax is used.
msg315553 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2018-04-21 07:21
In Python 2, you have to override __getslice__ as well as __getitem__.

Try this instead:


class MyTuple(tuple):
    def __getitem__(self, pos):
        print "get item {}".format(pos)
        return super(MyTuple, self).__getitem__(pos)
    def __getslice__(self, *args):
        print "get slice {}".format(args)
        return super(MyTuple, self).__getslice__(*args)


I don't believe this is a bug. If you try with the above fix, and still believe there is a bug, please feel free to re-open the issue.
msg315554 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-04-21 07:23
In Python 2 things are more complex than in Python 3. You have to define __getslice__ for handling the case of literal slices.

This was fixed in Python 3.
History
Date User Action Args
2018-04-21 07:23:10serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg315554
2018-04-21 07:21:09steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg315553

resolution: not a bug
stage: resolved
2018-04-21 06:47:32jpthalmancreate