array-api icon indicating copy to clipboard operation
array-api copied to clipboard

Adding `casting` argument to `astype` (and other casting functions/methods)

Open jakirkham opened this issue 2 years ago • 3 comments

Based on recent discussion, current astype behaves as if casting is set "unsafe". It may be worthwhile to add this argument as default "unsafe" while also allowing it to be configured. In particular "safe" may be of interest to allow users to catch any unexpected or unintended castings in library code. This casting flag may be useful in other places where castings occur.

jakirkham avatar Jul 07 '22 17:07 jakirkham

For astype it seems good to me to allow it in the sense of "unsafe" casting.

However, somehow, complex -> int/float does seem less well defined then float -> int. Python has it this way, since int(1.5) is OK, but int(1j) or float(1j) is not.

So when it comes to arr.astype() I am not yet certain about removing the warning from the NumPy main namespace. But with a warning astype(complex_arr, real) seems not super useful from a library perspective (you will need to use arr.real or real(arr) to avoid the warning).

Surprisingly, am not even certain that a complex -> real needs to be defined at all (as a proper cast), are there use-cases where you need it to work but calling real() or arr.real is not clearer?

seberg avatar Jul 07 '22 20:07 seberg

Interesting thanks for the context.

No strong feelings about the warning in NumPy.

Main interest here is ensuring library authors don't run into subtle bugs or at least have easy ways of avoiding them. That said, maybe it is worth thinking about expectations of safe casting.

Yeah the use case for complex -> real is what I was wondering as well in this comment ( https://github.com/data-apis/array-api/pull/445#issuecomment-1148024033 ). Also not clear on why it is needed.

jakirkham avatar Jul 07 '22 20:07 jakirkham

Yeah the use case for complex -> real is what I was wondering as well in this comment ( https://github.com/data-apis/array-api/pull/445#issuecomment-1148024033 ). Also not clear on why it is needed.

Trying to look at this from a different angle, I hope. Based on #427 (real) and #446 (conj) I think we are leaning toward a more restrictive API design as opposed to permissive. I seem to remember the permissive choice was favored during one of the meetings, but I can't recall it was for which library (and I also forgot which side I picked, I'd say restrictive but I am not certain anymore after a long week...😅) That's probably why I let go in #445 (astype). But, for the sake of consistency it'd be nicer if astype does not allow complex -> real?

cc: @kgryte

leofang avatar Jul 08 '22 00:07 leofang

In the specification, we opted to be restrictive in disallowing complex -> real. As such, I will go ahead and close this issue.

kgryte avatar Jun 29 '23 08:06 kgryte