[Python 3.4] Rationale for readonly slice data attributes

Ian Kelly ian.g.kelly at gmail.com
Fri Mar 6 01:36:47 EST 2015


On Thu, Mar 5, 2015 at 4:57 PM, Mario Figueiredo <marfig at gmail.com> wrote:
> What is the rationale behind making the slice class data attributes
> readonly?
>
> I've built a __getitem__ method for a Map class that contains a list
> of Cell instance objects. __getitem__ maps this list into a matrix::
>
>     # get cell at cartesian coordinates 12, 4
>     # will map to the 1048th position in the cells list
>         mmap = Map()
>     print(mmap[12, 4])
>
> All is working well and it even supports slicing::
>
>         # return all cells with x between 3 and 6 and y up until 4
>         mmap = Map()
>     [print(cell) for cell in mmap(3:6, :4)]
>
> This last example is one case in which I missed the ability to change
> the the `start` and `stop` attributes of the slice class in order for
> the maping to occur that allows a 2-dimensions access to a 1-dimension
> list.

I'm not following what it is that you want to accomplish in this
example by modifying the slice object.

> It was solved by taking another turn, but it proved to me that the
> slice data attributes are more useful if they are writable, and this
> clashes tremendously with the principles of data encapsulation that
> underline the requirements for a readonly property. In other words, if
> it needs to be accessed, don't hide it. If it needs to be written,
> don't lock it.
>
> Now, normally I take these things for granted. Rules are rules and
> their reasons are often fairly obvious. But in this case I'm at loss.
> I can't find a reason for this class attributes to have been made into
> readonly properties.

You also can't mutate bound methods, range objects, or ints. Do any of
those bother you?

Immutable types are often desirable because they're easier to reason
about, especially when concurrency enters the picture. As an example,
suppose I'm iterating over a view constructed by slicing some
collection. What should happen if the slice is suddenly altered in
mid-iteration? Because slice objects are immutable, this is a question
that doesn't even need an answer.

slice is about as light-weight a class as they come. If you need to
modify a slice, is there any reason you can't just construct a new
one?

Lastly, if you really want a mutable "slice", you can work around this
by using a 3-element list and construct a slice from it on demand.



More information about the Python-list mailing list