9

I am trying to write a BitArray class, and it would be nifty to have something like numpy's array, x[i:j:k] = val.

How would I write this in Python? Not with the __setslice__, right? Because that only takes three arguments and I need one to take four.

1
  • What four arguments do you want to pass? Commented Aug 24, 2012 at 1:25

2 Answers 2

6

__setslice__ is deprecated - you'll want to use __setitem__ with a slice argument.

Note that, per the Python documentation, slices can only be done in the following syntactic forms: a[i:j:step], a[i:j, k:l], or a[..., i:j]. The colon-based syntax is used to define a single slice object, but as the second example shows you can have multiple slice arguments (they get passed in as a tuple of slices).

Here's an example which prints the key argument, to see its form:

>>> class Foo(object):
>>>     def __setitem__(self, key, value):
>>>         print key
>>> 
>>> a = Foo()
>>> a[1:1] = 1
slice(1, 1, None)
>>> 
>>> a[1:1:1] = 1
slice(1, 1, 1)
>>> 
>>> a[1:1, 1:1] = 1
(slice(1, 1, None), slice(1, 1, None))
Sign up to request clarification or add additional context in comments.

1 Comment

There's some sample code at the bottom of docs.python.org/release/2.3.5/whatsnew/section-slices.html that is actually still useful for these purposes; it (more or less) documents the otherwise-undocumented indices method of slice objects, without which implementing a fully-general setitem on slices is fairly difficult.
1

__setslice__ is deprecated, see the Python 3 changelog:

__getslice__(), __setslice__() and __delslice__() were killed. The syntax a[i:j] now translates to a.__getitem__(slice(i, j)) (or __setitem__() or __delitem__(), when used as an assignment or deletion target, respectively).

Similarly, you can pass a step value to slice() which means the syntax a[i:j:k] translates to a.__getitem__(slice(i, j, k)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.