Closed to24toro closed 1 year ago
One concern this raises is that using numpy's ArrayLike
may imply that anything implementing __array__
is valid, whereas we want to imply something more vague than that: ArrayLike
means anything that a given instance of a numpy alias recognizes :).
This makes me lean towards defining our own ArrayLike
, and documenting that it is synonymous with whatever is returned by Alias.registered_types()
. @chriseclectic do you think it would make sense to add a static class property to Alias
generically called something like RegisteredType
, and we can override it for numpy_alias
to return ArrayLike
? (Or maybe ArrayliasLike
?) So, e.g. in a file in Dynamics, we could do:
from qiskit_dynamics.arraylias_state import DYNAMICS_ALIAS
ArrayLike = DYNAMICS_ALIAS.RegisteredType
def some_function(a: ArrayLike, b: ArrayLike):
...
For comparison, JAX defines their own ArrayLike
here. This isn't really analogous to the intended vagueness of what we're trying to do, but I just thought it was interesting they used the same type-hint name.
My concerns consist of two points.
ArrayLike
defined in numpy
contains a type List
. But there may be a situation we want to limit the type to either np.array
or jnp.array
. I think that a scope of a type hint is sufficient to cover only anything including an attribute array. Is it correct ?isinstance
. We cannot use ArrayLike
defined in numpy
in this case.
E.g. we could define:
@runtime_checkable
class ArrayLike(Protocol):
def __array__(self):
pass
If we use this ArrayLike
, we use it as a type hint that has array and can use
isinstance(np.array([1.2]), ArrayLike)
It is one way of defining our own ArrayLike
.
Summary
I tested arraylike demo in the notebook.
Details and comments
In docs(https://numpy.org/devdocs/reference/typing.html#numpy.typing.ArrayLike),
Among others this includes the likes of:
Scalars.
(Nested) sequences.
Objects implementing the array protocol.
So, we can use ArrayLike as a type hint which includes List, numpy.array, jax.numpy.array, and tensorflow.Tensor.