On Tue, Jul 11, 2023 at 2:38 PM James Webber <jamestweb...@gmail.com> wrote:

> Hello there! First time posting here and I apologize if this discussion is
> not new. I couldn't find it in a search.
>
> I've been contributing a bit to the sparse project (
> https://github.com/pydata/sparse) and I was working on specializing the
> behavior for single-argument ufuncs, because there is a faster path for
> some sparse arrays if the indexes don't change at all.
>
> As I was working on this I noticed that `sparse` uses `__array_ufunc__` on
> some non-ufunc methods, like `round`, `clip`, and `astype`, which caused
> some bugs in my initial attempt. This is easy enough to fix in the package,
> but it made me wonder if those functions _could_ or _should_ be ufuncs in
> numpy itself.
>
> The full list for the sparse library is `clip`, `round`, `astype`, `real`,
> and `imag`. There might be other candidates in numpy, those are just the
> ones in this project.
>
> The benefit I see is that an implementor of `__array_ufunc__` wouldn't
> need to implement these methods. But perhaps their interfaces are too
> complex for ufunc-iness?
>

In principle changing functions into ufuncs is fine I think, and it can
help performance and maintainability. The signatures of these functions
seem fine in principle. However, the devil is usually in the details - for
example:

>>> x = np.arange(5)
>>> class AClass:
...     def __init__(self, x):
...         self._x = x
...
...     def clip(self, x, a_min, a_max):
...         return self._x
...
>>> AClass(x).clip(x, 0, 1)
array([0, 1, 2, 3, 4])


That's due to `clip` being implemented with `_wrapfunc` under the hood. All
those "call methods with the same name from functions" are arguably design
mistakes, however unless we consciously decide to get rid of all of that at
once, we have to continue to support them.

It's hard to say more without trying; I think you could attempt to convert
one function and see how it goes.

Cheers,
Ralf
_______________________________________________
NumPy-Discussion mailing list -- numpy-discussion@python.org
To unsubscribe send an email to numpy-discussion-le...@python.org
https://mail.python.org/mailman3/lists/numpy-discussion.python.org/
Member address: arch...@mail-archive.com

Reply via email to