[Python] New generic type hints (python 3.12+) for numpy

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    What would be correct type hint notation for functions working with numpy arrays?

    is this correct way to implement generic type hints for numpy 2+ and python 3.12 +?

    I would like to implement even shape options into it as I noticed that numpy 2+ should allow that, but I got to admit, that I did not find consistent way that would satisfy mypy.

    Even in this example I have # type: ignore in the end. Can this be handled better?

    def calculate_signed_von_mises_principal[T: np.floating](
    first_principal: NDArray[T],
    second_principal: NDArray[T],
    third_principal: NDArray[T],
    ) -> NDArray[T]:
    unsigned_von_mises = np.sqrt(
    (
    (first_principal - second_principal) ** 2
    + (second_principal - third_principal) ** 2
    + (third_principal - first_principal) ** 2
    )
    / 2.0
    + 1e-12
    )
    hydrostatic_stress = (first_principal + second_principal + third_principal) / 3.0
    signed_von_mises = np.copysign(unsigned_von_mises, hydrostatic_stress)
    return signed_von_mises # type: ignore

    Continue reading...

Compartilhe esta Página