numpy type annotation

About_work·2023년 2월 24일
0

numpy

목록 보기
3/8

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)  # convert to a NumPy array
   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)

profile
새로운 것이 들어오면 이미 있는 것과 충돌을 시도하라.

0개의 댓글