com
com

Reputation: 79

Parsing slice information from a slice object?

I'm trying to get the information from a slice. Here's the start of my function. (I have tried "elif isinstance(key, slice):" for the fourth line and can't get that to work)

    def __getitem__(self, key):
    if isinstance(key,(int, long)):
        #do stuff if an int
    elif #item is slice
        #do stuff if a slice

If I make a function call of obj[4:6] to call this function and I print the "key" variable in the function, it prints "slice(4,6, None)" How do I parse the 4 and 6 values? What I"m trying to do is be able to use the data from the list inside the function.

Upvotes: 1

Views: 258

Answers (2)

BrenBarn
BrenBarn

Reputation: 251408

If you want the info from the slice object, access its attributes start, stop, and step. These attributes are documented here.

Upvotes: 0

mgilson
mgilson

Reputation: 309949

>>> slice(4,5).start
4
>>> slice(4,5).stop
5
>>> slice(4,5).step  #None

One particularly useful method of the slice object is the indices method:

>>> slice(4,5).indices(12)
(4, 5, 1)

You might use it like this:

 for i in range(*my_slice.indices(len(self))):
     print self[i]

Note that this really shines with negative indices or steps:

>>> slice(4,-5).indices(12)
(4, 7, 1)
>>> print range(*slice(None,None,-1).indices(12))
[11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Upvotes: 5

Related Questions