Loving TypeScript, but also math, thus numpy, thus needing python, I'm currently checking out how much typing can be brought to the python world. It's limited, it seems, and I have a particularly weird case, which I hope somebody can explain to me:
Using a module like
# testModule.py
import numpy.typing as npt
coordsType = list[tuple[float, float]] | list[list[float]] | npt.NDArray
def moduleFuncExplicit(arg: list[tuple[float, float]] | list[list[float]] | npt.NDArray):
return arg
def moduleFuncWithTypeVar(arg: coordsType):
return arg
and using these functions from another file like
# testMain.py
import testModule
import numpy as np
arg: list[tuple[float, float]] = [(1.,2.), (3.,4.), (5.,6.)]
npArg = np.array(arg, dtype=np.float64)
npArgAnyDtype = np.array(arg)
ret_Explicit_Simple = testModule.moduleFuncExplicit(arg)
ret_Explicit_Numpy = testModule.moduleFuncExplicit(npArg)
ret_TypeVar_Simple = testModule.moduleFuncWithTypeVar(arg)
ret_TypeVar_Numpy = testModule.moduleFuncWithTypeVar(npArg) # type error
ret_TypeVar_NumpyAny = testModule.moduleFuncWithTypeVar(npArgAnyDtype)
gives me a type error (only) for the fourth line:
Argument of type "NDArray[float64]" cannot be assigned to parameter "arg" of type "coordsType[Unknown]" in function "moduleFuncWithTypeVar"
Type "NDArray[float64]" cannot be assigned to type "coordsType[Unknown]"
"NDArray[float64]" is incompatible with "list[tuple[float, float]]"
"NDArray[float64]" is incompatible with "list[list[float]]"
TypeVar "_DType_co@ndarray" is covariant
TypeVar "_DTypeScalar_co@dtype" is covariant
Type "float64" cannot be assigned to type "ScalarType@NDArray"PylancereportGeneralTypeIssues
- What does this error mean? Why does it occur?
- More importantly, why the hell are the two module functions not exactly identical?