47

I would like a function to include a type hint for NumPy ndarray's alongside with its dtype.

With lists, for example, one could do the following...

def foo(bar: List[int]):
   ...

...in order to give a type hint that bar has to be list consisting of int's.

Unfortunately, this syntax throws exceptions for NumPy ndarray:

def foo(bar: np.ndarray[np.bool]):
   ...

> np.ndarray[np.bool]) (...) TypeError: 'type' object is not subscriptable

Is it possible to give dtype-specific type hints for np.ndarray?

4
  • 1
    Last time I answered a type-hinting question I couldn't find much numpy specific information
    – hpaulj
    Feb 3, 2019 at 17:28
  • 1
    What is List. list with lowercase is a normal Python function/type.
    – hpaulj
    Feb 3, 2019 at 18:29
  • Give a fuller context - what typing are you importing? How are you using typing? What numpy specific typing have you found and imported?
    – hpaulj
    Feb 3, 2019 at 18:35
  • 1
    @hpaulj, List is a built in mypy type: mypy.readthedocs.io/en/stable/builtin_types.html#built-in-types
    – th3coop
    Jan 13, 2021 at 15:58

4 Answers 4

49

You could check out nptyping:

from nptyping import NDArray, Bool

def foo(bar: NDArray[Bool]):
   ...

Or you could just use strings for type hints:

def foo(bar: 'np.ndarray[np.bool]'):
   ...
4
  • 1
    What does using stringy type hints do? Just show up as documentation? Or can editors actually parse them and enforce them? Sep 12, 2019 at 0:49
  • 5
    It serves as documentation and doesn't really do much (unless you start parsing them using inspection for some reason). Some editors (e.g. PyCharm) are smart enough though to see if they can make sense of textual type hints. Sometimes you'll have no other choice than to use textual type hints. For example when hinting a method's parameter to be of the same type of the class that holds the method.
    – R H
    Sep 12, 2019 at 20:18
  • 13
    Note that this is now accessible at numpy.typing.NDArray as of 1.20, not an external package: numpy.org/devdocs/reference/typing.html Aug 12, 2021 at 16:40
  • @RH you can add from __future__ import annotations to properly type-hint a method that accepts a parameter with the same type as the class it's defined in.
    – Just Me
    Mar 2, 2023 at 9:42
25

Check out data-science-types package.

pip install data-science-types

MyPy now has access to Numpy, Pandas, and Matplotlib stubs. Allows scenarios like:

# program.py

import numpy as np
import pandas as pd

arr1: np.ndarray[np.int64] = np.array([3, 7, 39, -3])  # OK
arr2: np.ndarray[np.int32] = np.array([3, 7, 39, -3])  # Type error

df: pd.DataFrame = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]}) # OK
df1: pd.DataFrame = pd.Series([1,2,3]) # error: Incompatible types in assignment (expression has type "Series[int]", variable has type "DataFrame")

Use mypy like normal.

$ mypy program.py

Usage with function-parameters

def f(df: pd.DataFrame):
    return df.head()

if __name__ == "__main__":
    x = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6]})
    print(f(x))

$ mypy program.py
> Success: no issues found in 1 source file
6
  • 1
    Yes, thank you for asking, I tested to make sure. Will extend answer with example. Jan 2, 2021 at 7:58
  • When executing scripts that use this library, I still get the TypeError: 'type' object is not subscriptable. So, PyCharm doesn't give a type warning anymore, but there is an error when executed. Feb 3, 2021 at 15:00
  • Are you getting this for the pd.DataFrame or for Numpy? I have gotten this before but I forget how I reproduced it. I'm also not in PyCharm, this was just using the terminal of JupyterLab to run the .py file. Feb 5, 2021 at 18:37
  • I've installed mypy and data-science-types and when I try the example I'm getting error: "ndarray" expects no type arguments, but 1 given. Any solution? I found sth about installing mypy from repo but it doesn't seem to work.
    – maciejwww
    May 17, 2021 at 19:06
  • 7
    From data-science-types github: ⚠️ this project has mostly stopped development ⚠️ The pandas team and the numpy team are both in the process of integrating type stubs into their codebases, and we don't see the point of competing with them. Oct 1, 2021 at 20:26
14

To the best of my knowledge it's not possible yet to specify dtype in numpy array type hints in function signatures. It is planned to be implemented at some point in the future. See numpy GitHub issue #7370 and numpy-stubs GitHub for more details on the current development status.

10

One informal solution for type documentation is the following:

from typing import TypeVar, Generic, Tuple, Union, Optional
import numpy as np

Shape = TypeVar("Shape")
DType = TypeVar("DType")


class Array(np.ndarray, Generic[Shape, DType]):
    """
    Use this to type-annotate numpy arrays, e.g.

        def transform_image(image: Array['H,W,3', np.uint8], ...):
            ...

    """
    pass


def func(arr: Array['N,2', int]):
    return arr*2


print(func(arr = np.array([(1, 2), (3, 4)])))

We've been using this at my company and made a MyPy checker that actually checks that the shapes work out (which we should release at some point).

Only thing is it doesn't make PyCharm happy (ie you still get the nasty warning lines):

enter image description here

1
  • I am very happy to hear that!!! Please release the checker as soon as you can!:) Or a stub file or something.
    – bogec
    Nov 22, 2020 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.