[Numpy-discussion] Type annotations for NumPy
Robert T. McGibbon
rmcgibbo at gmail.com
Tue Nov 28 17:35:55 EST 2017
Here's the code: https://github.com/rmcgibbo/numpy-mypy.
It's not 100% working yet, but it can do simple stuff, like inferring the
shape of arrays created from np.zeros(literal_tuple), and fixing out the
shape of the result of an indexing operation (i.e.
To implement it, I have the beginnings of the stubs that you'd expect,
borrowed from https://github.com/machinalis/mypy-data and then revised.
Then, on top of that, I wrote some special type-level functions that are
implemented inside of a mypy plugin. So, for example,
the stub's signature for np.sum is
def sum(a: ndarray[_S, _D], axis: AxesType=None, dtype: DtypeType=None, out:
ndarray=None, keepdims: bool=False) -> ndarray[_InferDtypeWithDefault[_S],
When the stub is applied, the resut's dtype is determined application of
the _InferDtypeWithDefault type function, which defaults, as expected, to
the dtype of the input array but checks of that was overridden dtype=None
kwarg as well. And the _InferNdimsReduction type function has to check the
axis and keepdims arguments as well.
It's by no means ready for real users, but I hope this is a useful place to
build from. Any feedback or contributions would be appreciated.
On Tue, Nov 28, 2017 at 2:04 PM, Stephan Hoyer <shoyer at gmail.com> wrote:
> On Tue, Nov 28, 2017 at 5:11 PM Robert T. McGibbon <rmcgibbo at gmail.com>
>> I'm strongly in support of this proposal. Type annotations have really
>> helped me write more correct code.
>> I started working on numpy type stubs a few months ago. I needed a mypy
>> plugin to support shape-aware functions. Those whole thing is pretty
>> tricky. Still very WIP, but I'll clean them up a little bit and opensource
>> it shortly.
> Great to hear -- I'd love to see what this looks like, or hear any lessons
> you learned from the experience!
> Actual experience using and writing such a type checker gives you a
> valuable perspective to share, as opposed to my speculation.
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion