ENH: Make numpy scalars subtypes of their builtin counterpart#17117
ENH: Make numpy scalars subtypes of their builtin counterpart#17117BvB93 wants to merge 9 commits intonumpy:masterfrom
Conversation
|
At a glance, I think I prefered the alternative in #17096 - numpy scalars are frequently not a drop-in for python ones, and that type of mistake seems like something it would be nice for mypy to catch. With this PR, it forces it to be a runtime error. |
numpy/tests/typing/pass/scalars.py
Outdated
There was a problem hiding this comment.
As an example of why I think this is a mistake, mypy will allow this code even though it raises AttributeError:
def func_int(a: int) -> None:
return a.to_bytes(1, byteorder="little")
func_int(np.int8(1))There was a problem hiding this comment.
Note that there are already a few of such cases in mypy, as int does not implement all methods which exists in float.
>>> def func(a: float) -> bool:
... return a.is_integer()
# NOTE: mypy considers `int` a subclass of `float`
>>> func(1)
Traceback (most recent call last):
...
AttributeError: 'int' object has no attribute 'as_integer'The number cases where the int / np.integer does work is substantially larger then those were it doesn't (just as with int & float), to the point where I feel a more pragmatic approach is justified.
There was a problem hiding this comment.
Note that the problems with int vs float are slowly being resolved by adding the missing methods (https://bugs.python.org/issue26680)
…p.timedelta64` Partially reverts ed18dd33d0d9a3da65f2bf5600f3664b1d2a577a
Co-Authored-By: Eric Wieser <eric-wieser@users.noreply.github.com>
|
Rebased to get rid of a merge conflict. |
|
@BvB93 there is a merge conflict. |
|
I agree with @eric-wieser that I think this approach would be a mistake. NumPy scalars are not fully drop-in compatible with Python scalars, and pretending they are can lead to subtle bugs. A few examples that come to mind:
|
|
Closing this for now, as the consensus appears to be that the potential advantages do not outweigh the disadvantages. |
Closes #17105.
This pull request modifies the superclasses of six
np.genericsubclasses:Moved to MAINT: Fix various issues with thenp.str_&np.bytes_are now, respectively, subclasses ofstr&bytes.This relation is also true during runtime, so this is actually a fix rather than an enhancement.
np.genericannotations #17214.np.floating&np.complexfloatingare now, respectively, treated as subclasses offloat&complex.During runtime this relation does, strictly speaking, only hold for
np.float64andnp.complex128.np.integeris now treated as a subclass ofint. This relation does not hold during runtime.A few notes on a number of untouched classes:
np.timedelta64&np.datetime64are surprisingly incompatible with their counterparts indatetime.boolcan, unfortunately, not be subclassed (even in stub files).Lastly, this pull request serves as an alternative to #17096.
Examples