NumPy:Typing
numpy.ndarray
import numpy as np
def some_function(x: np.ndarray, y: np.ndarray) -> np.ndarray:
return x + y
ArrayLike
- 정확한 type은 구체화되지 않았지만, array-like object가 될 수 있는 친구들에 사용
- lists, tuples, and NumPy arrays와 같은 친구들
- 사용 타이밍:
- array-like objects의 여러 다른 types을 받을 수 있게 함수를 구성하고 싶을 때. (Flexibility를 얻고 싶을 때)
- 특정 함수가 특정 datatype으로 바꿔주는 preprocessing 역할을 할 때
from numpy.typing import ArrayLike
def compute_mean(x: ArrayLike) -> float:
x_arr = np.array(x) # convert to a NumPy array
return np.mean(x_arr)
NDArray
from numpy import uint8
from numpy.typing import NDArray
def addimg(image: NDArray[uint8]) -> None:
...
from typing import TypeVar
from numpy.typing import NDArray
import numpy as np
T = TypeVar('T', bound=np.generic)
def process_2d_array(arr: NDArray[T]) -> NDArray[T]:
# 2D 배열에만 허용되는 함수 내용
assert arr.ndim == 2, "Input array must be 2D"
return arr * 2
See also