ArrayLike?
- 정확한 type은 구체화되지 않았지만, array-like object가 될 수 있는 친구들에 사용
- lists, tuples, and NumPy arrays와 같은 친구들
언제 쓰면돼?
- array-like objects의 여러 다른 types을 받을 수 있게 함수를 구성하고 싶을 때.(flexibility를 얻고 싶을 때)
- 다양한 input을 받도록 고려하여 함수를 개발하는 것은 매우 좋은 습관
- 특정 함수가 특정 datatype으로 바꿔주는 preprocessing 역할을 할 때
from numpy.typing import ArrayLike
def compute_mean(x: ArrayLike) -> float:
x_arr = np.array(x)
return np.mean(x_arr)
언제 쓰면 안돼?
- type을 구체화할 수 있는데(해야 하는데), 안하려는 목적으로 쓰면 안됨
np.ndarray
import numpy as np
def some_function(x: np.ndarray, y: np.ndarray) -> np.ndarray:
return x + y
numpy.typing.NDArray
numpy.ndarray
보다 더 구체적인 type hint이다. (data type을 준다.)
언제 쓰면 돼?
- numpy array의 구체적인 data type 정보를 포함하고 싶을때
from numpy.typing import NDArray
import numpy.typing as npt
print(npt.NDArray[np.float64])
>>> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
def generate_random_array() -> NDArray[np.float64]:
return np.random.randint(0, 10, size=(10,))
NDArrayInt = npt.NDArray[np.int_]
a: NDArrayInt = np.arange(10)