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

Write protocol class for numpy.ndarray #48

Open
MilanStaffehl opened this issue Jul 13, 2024 · 1 comment
Open

Write protocol class for numpy.ndarray #48

MilanStaffehl opened this issue Jul 13, 2024 · 1 comment
Assignees
Labels
feature: typing New feature for array typing
Milestone

Comments

@MilanStaffehl
Copy link
Owner

The numpy.ndarray class has an invariant shape parameter. While there is a PR at the numpy repo that will make it covariant, this change will probably not be backported, so we are still stuck with an invariant shape in all versions prior to this change.

As a result, assignements such as the following are causing type checking errors:

from numdantic import NDArray
import numpy as np

x: NDArray[tuple[int, int], np.int32] = ...
y: NDArray[tuple[int, ...], np.int32] = x  # <-- error: Incompatible types in assignment

This is despite the fact that tuple[int, int] is a valid subtype of tuple[int, ...], but since the shape parameter is invariant, the assignment is still rejected. The "easiest" way I see to circumvent this problem is to create a protocol class for the numpy.ndarray class which has a covariant shape as type parameter.

To perfectly mimic the entire interface of the class, this would require a lot of boilerplate. However, this would ensure that types behave as intended and would get rid of the problem of being unable to mix int, Literal and named axes in shapes, while maintaining the type safety that using ndarray directly has.

@MilanStaffehl MilanStaffehl added the feature: typing New feature for array typing label Jul 13, 2024
@MilanStaffehl MilanStaffehl added this to the 0.2.0 milestone Jul 13, 2024
@MilanStaffehl MilanStaffehl self-assigned this Jul 13, 2024
@MilanStaffehl
Copy link
Owner Author

The numpy PR for making shape covariant has been merged and is scheduled to be released with numpy 2.1.0, so this can be included immediately as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature: typing New feature for array typing
Projects
None yet
Development

When branches are created from issues, their pull requests are automatically linked.

1 participant