Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Embed the possible dtype-likes in the scalar types #138

Open
jorenham opened this issue Feb 14, 2025 · 0 comments
Open

Embed the possible dtype-likes in the scalar types #138

jorenham opened this issue Feb 14, 2025 · 0 comments

Comments

@jorenham
Copy link
Member

This uses the same trick as in #137, and it also requires #136 to be resolved first. It isn't as useful as #137, because it requires both the protocol and the scalar type to be on the left-hand-side of the signature, which e.g. is (or could me made) the case in the constructors of dtype and {f,i}info.

from numpy._typing._char_codes import _Int16Codes
from numpy._typing._dtype_like import _DTypeLike

class int16(signedinteger[_16]):
    @type_check_only
    def __dtype_like__(self) -> _DTypeLike[int16] | _Int16Codes: ...  # fictional
    @property
    def dtype(self) -> np.dtypes.Int16DType: ...
    ...

Do this for all scalar types, including the abstract ones. This way, we can create a generic "inverted npt.DTypeLike" protocol:

class _CanDTypeLike[T, DT: dtype[Any]](Protocol):  # both are covariant
    def __dtype_like__(self) -> T: ...
    @property
    def dtype(self) -> DT: ...

class _HasType[T](Protocol):  # covariant
    @property
    def type(self) -> type[T]: ...

type HasTypeLike[T, DT: dtype[Any]] = _HasType[_CanDTypeLike[T, DT]]

Assuming that the constraint solver of the type-checker is powerful enough, this could then be used in e.g. dtype to simplify the constructor:

class dtype[SCT_co: generic]:
    @overload
    def __new__[T, DT: dtype[Any]](
        cls: HasTypeLike[T, DT],
        dtype: T,
        align: py_bool = False,
        copy: py_bool = False,
        metadata: Mapping[str, Any] = ...,
    ) -> DT: ...
    @overload
    def __new__(
        cls,
        dtype: npt.DTypeLike,
        align: py_bool = False,
        copy: py_bool = False,
        metadata: Mapping[str, Any] = ...,
    ) -> dtype[Any]: ...

But now that I see it, might be expecting a bit too much, especially in case of mypy... Any, I guess it's still worth a shot 🤷🏻

@jorenham jorenham changed the title Embed the dtype-likes in the dtype types Embed the possible dtype-likes in the scalar types Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant