[Numpy-discussion] Ransom Proposals
Tim Hochberg
tim.hochberg at cox.net
Sun Mar 26 20:34:01 EST 2006
Bill Baxter wrote:
>
>
> On 3/26/06, *Fernando Perez* <Fernando.Perez at colorado.edu
> <mailto:Fernando.Perez at colorado.edu>> wrote:
>
> > Or, you can use the reshape method instead of function. I believe
> > numpy advocates use of methods instead of functions. What you
> observe
> > is just another reason for that. Since functions like reshape
> remain
> > in numpy primarily for backwards compatibility, I would be
> against any
> > change in semantics.
>
> Mmh. I bet many people will continue to use the functional
> interface for a
> long time.
>
>
>
> And maybe they'd be right to want a functional interface, too:
> http://www.gotw.ca/gotw/084.htm
>
>
> The author argues that in general, you should make as few functions as
> possible be members of a class, always preferring non-member functions
> wherever possible. It's about C++, but the principle should apply to
> Python as well. It does make a certain kind of sense, although the
> article seems to completely ignore polymorphism, which seems like it
> would be another good reason to have functions be members, at least in
> C++.
Personally, I've always prefered the functional interface, but it
appears that for historical / backwards compatibility reasons our choice
is between a functional interface that is broken and a working method
based interface. For that reason alone, I'm now in favor of ditching the
functional interface to 'reshape' and 'transpose'.
As to whether 'reshape' and 'transpose' should be functions or methods
in an ideal world, I think it's worth considering them together. It's
straightforward to come up with a version of 'reshape' that's fairly
generic:
def reshape(obj, shape):
val = obj.view()
val.shape = shape
return val
[Unlike the current version of 'reshape', this one always returns a
view; that is on purpose] This will reshape any object that supports
both the 'view' method and the 'shape' attribute. Writing something
equivalent for 'transpose' does not appear possible. I could do
something like:
def transpose(obj, axes=None):
if axes == None:
axes = reversed(range(len(obj.shape)))
else:
axes = list(axes)
shape = numpy.asarray(obj.shape)[axes]
strides = numpy.asarray(obj.strides)[axes]
val = obj.view()
val.shape = shape
val.strides = strides
return val
However, while I consider it reasonable to require all array-like
objects to have 'view' and 'shape', I doubt that it's reasonable to have
them need 'strides' as well. What would 'strides' mean for a sparse
array for example? Therefore, 'transpose' should be a method. Since
I've always considered 'reshape' and 'transpose' a pair and would find
it disconcerting if one were a method while the other was a function
(this may be a personal foible however), so I'm coming to the view that
they should probably have been methods all along.
Regards,
-tim
More information about the NumPy-Discussion
mailing list