Repository navigation
Protocol for array objects #229
Description
I've tried to tackle static typing and got a vendorable protocol that can be checked statically as well as at runtime for all but one case I'm going to detail below.
Protocol
import enum
from typing import Any, Optional, Protocol, Tuple, TypeVar, Union, runtime_checkable
A = TypeVar("A")
@runtime_checkable
class VendoredArrayProtocol(Protocol[A]):
@property
def dtype(self) -> Any:
...
@property
def device(self) -> Any:
...
@property
def ndim(self) -> int:
...
@property
def shape(self) -> Any:
...
@property
def size(self) -> int:
...
@property
def T(self) -> A:
...
def __abs__(self) -> A:
...
def __add__(self, other: Union[int, float, A], /) -> A:
...
def __and__(self, other: Union[bool, int, A], /) -> A:
...
def __array_namespace__(self, /, *, api_version: Optional[str] = None) -> Any:
...
def __bool__(self) -> bool:
...
def __dlpack__(self, /, *, stream: Optional[Union[int, Any]] = None) -> Any:
...
def __dlpack_device__(self) -> Tuple[enum.IntEnum, int]:
...
# This overrides the input type, since object.__eq__ handles any input
# This overrides the return type, since object.__eq__ returns a bool
def __eq__( # type: ignore[override]
self,
other: Union[bool, int, float, A],
/,
) -> A: # type: ignore[override]
...
def __float__(self) -> float:
...
def __floordiv__(self, other: Union[int, float, A], /) -> A:
...
def __ge__(self, other: Union[int, float, A], /) -> A:
...
def __getitem__(
self,
key: Union[int, slice, Tuple[Union[int, slice], ...], A],
/,
) -> A:
...
def __gt__(self, other: Union[int, float, A], /) -> A:
...
def __int__(self) -> int:
...
def __invert__(self) -> A:
...
def __le__(self, other: Union[int, float, A], /) -> A:
...
def __len__(self) -> int:
...
def __lshift__(self, other: Union[int, A], /) -> A:
...
def __lt__(self, other: Union[int, float, A], /) -> A:
...
def __matmul__(self, other: A) -> A:
...
def __mod__(self, other: Union[int, float, A], /) -> A:
...
def __mul__(self, other: Union[int, float, A], /) -> A:
...
# This overrides the input type, since object.__ne__ handles any input
# This overrides the return type, since object.__ne__ returns a bool
def __ne__( # type: ignore[override]
self, other: Union[bool, int, float, A], /
) -> A: # type: ignore[override]
...
def __neg__(self) -> A:
...
def __or__(self, other: Union[bool, int, A], /) -> A:
...
def __pos__(self) -> A:
...
def __pow__(self, other: Union[int, float, A], /) -> A:
...
def __rshift__(self, other: Union[int, A], /) -> A:
...
def __setitem__(
self,
key: Union[int, slice, Tuple[Union[int, slice], ...], A],
value: Union[bool, int, float, A],
/,
) -> None:
...
def __sub__(self, other: Union[int, float, A], /) -> A:
...
def __truediv__(self, other: Union[int, float, A], /) -> A:
...
def __xor__(self, other: Union[bool, int, A], /) -> A:
...To test everything yourself you can use this playground repo.
Current blocker
It is currently impossible to use Ellipsis in type annotations, since its alias ... has a different meaning there. Thus, it is currently impossible to correctly annotate the __getitem__ and __setitem__ methods. There is a fix for this in python/cpython/#22336, but it will only be shipped with Python 3.10. If we leave it out of the annotation, accessing the array with something like Array()[..., 0] will be flagged by mypy although it should be supported according to the specification.
Suggestes improvements
While working on the protocol I found a few issues that could be addressed:
-
Array.dtype,Array.device,Array.__array_namespace__(), andArray.__dlpack__()should return custom objects, but it is not specified how these objects "look like". In the current state of the protocol I've typed them asAny, but the specification should be more precise. -
Array.shapeshould returnTuple[int, ...], but explicitly check for Python scalars in constant tests array-api-tests#15 (comment) implies that custom objects might also be possible. Maybe we can useSequence[int]? -
The type annotation of the
streamparameter fromArray.__dlpack__()readsOptional[Union[int, Any]]which is equivalent toAnybut more concise. -
The binary dunder methods take a specific input types for the
otherparameter. For example__add__takesUnion[int, float, Array]. IMO they should takeAnyand returnNotImplementedin case they cannot work with the type. For example:class Array: def __add__(self, other: Any, /) -> "Array": if not isinstance(other, (int, float, Array)): return NotImplemented # perform addition
This makes it harder for static type checkers to catch bugs, because statically something like
Array() + Nonewould be allowed, but it gives theotherobject a chance to work with theArrayobject by implementing the reflected dunder (here__radd__). If both objects do not know how to deal with the addition, Python will automatically raise aTypeError.Since the
objectclass defines a__eq__and__neq__method according to the proposed scheme above, I needed to put# type: ignore[override]directives in the protocol for the input types.
Activity
BvB93 commentedon Jul 16, 2021
In general this seem like a perfect case for the use of a Protocol, so +1!
Based on my experience in the typing of numpy I do have a couple of comments:
Currently there exists the type-check-only
builtins.ellipsisclass that is used for this exact purpose.It's public status is somewhat questionable (python/typeshed#3556), but I'd argue that some pragmatism
is required here, as it is the only way of typing the
...singleton as of the moment.While
# type: ignorefixes the mypy error, it does not get rid of a more fundamental problem: nearly every single object supports comparison due toobject.__eq__. numpy/numpy#17368 (comment) contains a more complete example, but the general gist of it is that we can only describe what happens withVendoredArrayProtocol() == FooType(), but have zero control overFooType() == VendoredArrayProtocol()as this the domain ofFooType.__eq__and/orobject.__eq__.As a reminder: for
A() + B()to work, the__add__method of both types does not have to be symmetric. so even ifA.__add__does not supportBas argument, everything will work out fine as long asB.__add__does supportA.A practical example of this in practice would be
list.__mul__andint.__mul__, the former supporting the latter but not the other way around.On the subjects of shapes I'd like to point everyone's attention to PEP 646: Variadic Generics. Namelly, it'd allow us to define a single shape type that takes a variable number of parameters (i.e. axis lengths), just like tuple can be
Tuple[int],Tuple[int, int],Tuple[int, int, int], etc.. With this mind I'd suggest to either stick toTuple, or wait until PEP 646 is live and then defined a custom variadicSequencetype or protocol.For
__dlpack__specifically it should be quite easy to create a proper return type if we can getbuiltins.Pycapsuleannotated in typeshed (e.g. numpy/numpy#19083 (comment)). If not then it is always possible to create a custom type, but then we would have the issue that it'd have to be distributed from a single central place.pmeier commentedon Jul 16, 2021
Awesome, I didn't know or find that. This unblocks this and we could add the protocol to the specification. Current iteration:
Protocol
This is only true if
Bimplements__radd__:BvB93 commentedon Jul 16, 2021
Fair enough, I implicitly assumed that both
__add__and__radd__would be defined.Nevertheless, my point here is that there is no need here for
Anyas long as a custom user typehas properly annotated its
__add__and__radd__methods (which is the users responsibility).asmeurer commentedon Jul 16, 2021
The NotImplemented question came up in the NumPy PR as well (numpy/numpy#18585 (comment)).
My opinion is that the spec should not disallow returning NotImplemented but not require it. Libraries like NumPy have their own dispatching mechanism that isn't based on NotImplemented. I also think it should be out of scope for the spec to define how
__eq__works on unexpected types. An array library may want to work like NumPy where it absorbs things in__eq__, especially if it implements more dtypes than are in the spec, or it may want to return True/False (or NotImplemented), or just error. Any of those options are reasonable. I'm not sure how this affects typing, but it's also my opinion that the type hints should follow from the constraints of the spec, not the other way around.These are just my opinions though, so maybe others will disagree.
rgommers commentedon Jul 27, 2021
@pmeier can you summarize the issue with if every array library vendors this protocol, instead of putting it in a common package and inheriting from it? That still has a limitation, right?
"not allow" --> "allow" ?
+1 to wait for typeshed here (or go help them along if it starts taking too long).
Is there a problem with using
Tuple[int, ...]? I'd think that that is a little more specific than plainTuple, without it being a problem to change it to something even more specific later?asmeurer commentedon Jul 27, 2021
Yes that is what I meant.
pmeier commentedon Jul 28, 2021
@rgommers
Not sure what you mean here. If this is about my earlier concern (that I only voiced offline) that
typing.TypeVaronly works for directly related classes, this is not blocking anymore. Although the documentation statesit seems to work out fine with the vendored protocol, which by definition cannot be related to an actual array implementation. If you have a look at the playgorund repo and specifically this file,
mypyis happy although theArrayImplementationclass is independent ofVendoredArrayProtocol.Yes, see data-apis/array-api-tests#15 (comment). But this is not solved by variadic generics either IIUC.
pmeier commentedon Jul 28, 2021
I've tested the protocol against
numpyand apart from thedeviceattribute and thearray_namespace,dlpack, anddlpack_devicedunders,numpy.ndarray's check fine.BvB93 commentedon Jul 28, 2021
Right, to clarify: the reason for excluding subscription was for the sake of creating a compact example.
Assuming we won't run into any bugs with type checkers, the sole "issue" here would be code duplication.
rgommers commentedon Jul 28, 2021
Good. I'm not bothered by code duplication, I'm pretty sure that all array libraries will prefer that over adding a runtime dependency. However, we still need a way for downstream consumers to access this protocol - downstream packages may be less happy to vendor, and end users even less. That could be solved by:
We anyway will need a canonical version somewhere to ensure vendored copies can be updated and remain in sync. So it may be preferable to go with (1).
rgommers commentedon Jul 29, 2021
We had a discussion about this today. A standalone package may indeed be nice, and then we also have a place where other utilities or tests can be added (this has come up several times before, and we always tried to avoid a package because that's work to maintain - but here it seems like we can't avoid that anyway).
In terms of vendoring, it may be possible to avoid that by (in an array library) doing:
A number of libraries don't support static typing at all yet (TensorFlow, CuPy), while some others (NumPy, PyTorch, MXNet) do. Then the only libraries that may want to vendor the protocol are the ones that want to use it in their own test suite.
honno commentedon Dec 17, 2021
Related discussion (somehow totally missed this interesting issue agh)