__getitem__, __getslice__ question for python 2.2

logistix logstx at bellatlantic.net
Sat May 11 16:31:52 EDT 2002


Builtin types don't accept slice objects for some reason.  You need to
manually test to see if you got a slice or an int.  If it's a slice, you'll
probably need to use list.__getslice__ for it to work now, but you don't
need a seperate method in the test class.

Also, some people don't like to use isinstance, but I'm not sure how else to
tell if you got an int.


>>> import types
>>> def testForSlice(index):
...  if hasattr(index, "start"):
...   print "It's a slice [%s:%s]" % (index.start, index.stop)
...  elif isinstance(index, int):
...   print "It's an int => %s" % index
...  else:
...   raise TypeError
...
>>> testForSlice(1)
It's an int => 1
>>> sl = slice(1,2)
>>> testForSlice(sl)
It's a slice [1:2]
>>> sl = slice(2)
>>> testForSlice(sl)
It's a slice [None:2]
>>> testForSlice(1.2)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 7, in testForSlice
TypeError
>>>
--
-

"Edward C. Jones" <edcjones at erols.com> wrote in message
news:3CDD412D.3000805 at erols.com...
> In Python 2.2 the following code outputs [1, 2] but never gets to line 8:
>
>      class test(list):
>          def __init__(self, data=[]):
>              list.__init__(self, data)
>
>          def __getitem__(self, key):
>              print 'L8', key
>              return list.__getitem__(self, key)
>
>      #    def __getslice__(self, lo, hi):
>      #        print 'L12', lo, hi
>      #        return list.__getslice__(self, lo, hi)
>
>      x = test([0,1,2,3,4])
>      print x[1:3]
>
> If __getslice__ is uncommented, [1, 2] is output and line 12 is executed.
>
> What is going on here? What is the status of the deprecation of
> __getslice__? How does this all relate to the new style classes?
>
> Thanks,
> Ed Jones
>





More information about the Python-list mailing list