[Numpy-discussion] Ravel and inplace modification

Charles R Harris charlesr.harris@gmail....
Thu Mar 20 10:11:07 CDT 2008


On Thu, Mar 20, 2008 at 6:04 AM, Gael Varoquaux <
gael.varoquaux@normalesup.org> wrote:

> At the nipy sprint in Paris, we have been having a discussion about
> methods modifying inplace and returning a view, or returning a copy.
>
> The main issue is with ravel that tries to keep a view, but that
> obviously has to do a copy sometimes. (Is ravel the only place where this
> behavior can happen ?). We came up with the following scenario:
>
> Mrs Jane is an experienced Python developper, working with less
> experienced developpers. She has developped a set of functions to process
> data that assume they can use the ravel method returning a view. One day
> another programmes feeds it new kind of data. The functions work, but
> return something wrong.
>
> We (Stefan van der Walt, Matthew Brett and I) are suggesting that it
> would be a good idea to add a keyword to the ravel method so that it
> raises an exception if it cannot return a view. Stefan is proposing to
> implement it.
>
> What do people think about this? Should Stefan go ahead?
>

Ravel is not writeable, so it can't be used on the left side of assignments
where the view/copy semantics could be a problem.


 There was a long thread a couple of years ago concerning the reshape
method, which has the same problem. I think ravel should be avoided if the
user needs a guarantee that things will be done in place. So it is fine to
use it in expressions, but watch out if it is used as an lvalue. My
suggestion at the time was that the method should return a view or raise a
flag, while the function should always return a copy, but that solution has
the problem that functions with the same name behave in different ways. I
suppose one could also mark the returned data writeable=False, which would
certainly discourage assignments to it.

There are alternative methods: a.flatten will always return a copy and
a.flat will return an iterator. Perhaps those should be suggested in cases
where the user needs a particular behavior. As is, I don't think we can
change the behavior of ravel at this point. It has been around for too long
and such changes might break software. Better to clearly document its
problems and suggest alternatives.

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080320/34ec04b3/attachment-0001.html 


More information about the Numpy-discussion mailing list