<p dir="ltr">AFAICT the only real solution here is for np.sum and friends to propagate the keepdims argument if and only if it was explicitly passed to them (or maybe the slightly different, if and only if it has a non-default value). If we just started requiring code to handle it and passing it unconditionally, then as soon as someone upgraded numpy all their existing code might break for no good reason.</p>
<div class="gmail_quote">On May 5, 2015 8:13 AM, "Allan Haldane" <<a href="mailto:allanhaldane@gmail.com">allanhaldane@gmail.com</a>> wrote:<br type="attribution"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hello all,<br>
<br>
A question:<br>
<br>
Many ndarray methods (eg sum, mean, any, min) have a "keepdims" keyword<br>
argument, but ndarray subclass methods sometimes don't. The 'matrix'<br>
subclass doesn't, and numpy functions like 'np.sum' intentionally<br>
drop/ignore the keepdims argument when called with an ndarray subclass<br>
as first argument.<br>
<br>
This means you can't always use ndarray subclasses as 'drop in'<br>
replacement for ndarrays if the code uses keepdims (even indirectly),<br>
and it means code that deals with keepdims (eg np.sum and more) has to<br>
detect ndarray subclasses and drop keepdims even if the subclass<br>
supports it (since there is no good way to detect support). It seems to<br>
me that if we are going to use inheritance, subclass methods should keep<br>
the signature of the parent class methods. What does the list think?<br>
<br>
---- Details: ----<br>
<br>
This problem comes up in a PR I'm working on (#5706) to add the keepdims<br>
arg to masked array methods. In order to support masked matrices (which<br>
a lot of unit tests check), I would have to detect and drop the keepdims<br>
arg to avoid an exception. This would be solved if the matrix class<br>
supported keepdims (plus an update to np.sum). Similarly,<br>
`np.sum(mymaskedarray, keepdims=True)` does not respect keepdims, but it<br>
could work if all subclasses supported keepdims.<br>
<br>
I do not foresee immediate problems with adding keepdims to the matrix<br>
methods, except that it would be an unused argument. Modifying `np.sum`<br>
to always pass on the keepdims arg is trickier, since it would break any<br>
code that tried to np.sum a subclass that doesn't support keepdims, eg<br>
pandas.DataFrame. **kwargs tricks might work. But if it's permissible I<br>
think it would be better to require subclasses to support all the<br>
keyword args ndarray supports.<br>
<br>
Allan<br>
_______________________________________________<br>
NumPy-Discussion mailing list<br>
<a href="mailto:NumPy-Discussion@scipy.org">NumPy-Discussion@scipy.org</a><br>
<a href="http://mail.scipy.org/mailman/listinfo/numpy-discussion" target="_blank">http://mail.scipy.org/mailman/listinfo/numpy-discussion</a><br>
</blockquote></div>