Slice objects. How to apply them to strings?

logistix logstx at bellatlantic.net
Fri Mar 29 17:13:25 EST 2002


> >
> >If 'item' is a slice object, shouldn't I just be able to say:
> >
> >    self.s[item]
> >?
> >

Yes, it would be sensible.  No you can't do it.  For some reason you can't
apply slice objects to built-in types.  Ultimately, this is because slice
objects are just a hack for operator overloading purposes.  I honestly don't
know how difficult it would be to modify the interpreter to allow types to
accept slice objects, but I imagine it's one of the things on the list for
"class/type unification"

Here are a few things if you think your code is too ugly.  First of all,
"step" is not valid in builtin objects, so you can ignore that case.  You
can also use a boolean short-circuit trick to take care of start:

def __getitem__(self, item):
    if type(item) == types.IntType:
        return self.s[item]
    elif:
        return self.s[item.start or 0, item.stop]
    else:
        raise TypeError, "sequence index must be interger or slice object"

That's about as short as you can safely get on the routine.






More information about the Python-list mailing list