Skip to content
Search

NumPy:Typing

lastmod 2024-09-05created 2023-01-053 edits

numpy.ndarray

import numpy as np

def some_function(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    return x + y

ArrayLike

  • Used for things whose exact type isn't specified but that can be array-like objects
  • Things like lists, tuples, and NumPy arrays
  • When to use:
  • When you want to write a function that accepts several different types of array-like objects. (When you want flexibility)
  • When a function acts as preprocessing that converts input into a specific datatype
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:
    ...

How to apply typing.TypeVar

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

author Zer0 sitemap