Search code examples
pythonnumpydependencies

Unable to access 'numpy.typing' directly for static typing in NumPy 1.24.3


I'm trying to use the ArrayLike type from the numpy.typing module for static typing. I am using NumPy version 1.24.3.

When I import ArrayLike directly from numpy.typing, everything works as expected:

from numpy.typing import ArrayLike

def myfun(a: ArrayLike):
   pass

However, if I try to import numpy as np and then use np.typing.ArrayLike, I get an AttributeError.

With:

import numpy

def myfun(a: numpy.typing.ArrayLike):
   pass

The error I get is:

ERROR!
Traceback (most recent call last):
  File "<string>", line 4, in <module>
  File "/usr/local/lib/python3.11/site-packages/numpy/__init__.py", line 320, in __getattr__
    raise AttributeError("module {!r} has no attribute "
AttributeError: module 'numpy' has no attribute 'typing'

I'm not sure why I'm getting this error. I tried it on my local machine and in an online python interpreter with the same result.

Any insights would be greatly appreciated.


Solution

  • In a single Package like numpy, there are subpackages like typing. the file structure is similar to:

    numpy/
        __init__.py
        ...
        typing/
            ...
            __init__.py
            ...
    

    By using:

    from numpy.typing import ArrayLike
    

    you are importing the subpackage 'typing' from package 'numpy' and using the attribute ArrayLike. However, this:

    import numpy
    numpy.typing.ArrayLike
    

    only imports the numpy package. The second line treats "typing" as a value exported by numpy. However, "typing" is a subpackage. Therefore, it results in error.