英文:
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.
英文:
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.
答案1
得分: 0
在一个单独的包中,比如numpy,有像typing这样的子包。文件结构类似于:
numpy/
__init__.py
...
typing/
...
__init__.py
...
通过使用:
from numpy.typing import ArrayLike
你正在从包numpy
中导入子包typing
并使用属性ArrayLike
。
然而,这样做:
import numpy
numpy.typing.ArrayLike
只是导入了numpy包。第二行将"typing"视为由numpy导出的一个值。然而,"typing"是一个子包。因此会导致错误。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论