I would like to have function argument declarations in my Python code to make it more informative, to catch mismatched arguments, and to ease future automatic translation to Fortran. You can annotate scalar arguments with :int
or :float
, but I am having trouble annotating NumPy array arguments.
In Fortran one can declare an argument
real(kind=kind(1.0d0)) :: x(:)
and in Python one can write
from __future__ import annotations
import numpy as np
from nptyping import NDArray
def f(x:NDArray[np.float64]):
However, CPython does not check type annotations, and mypy, a tool that does, complains about such a declaration. For the code
from __future__ import annotations
import numpy as np
from statsmodels.tsa.arima_process import ArmaProcess
from nptyping import NDArray
def ar1_sim(nobs:int, ar1:float):
""" simulate an AR(1) autoregressive process """
ar_coeff = np.array([1, -ar1])
ma_coeff = np.array([1])
AR_object1 = ArmaProcess(ar_coeff,ma_coeff)
return AR_object1.generate_sample(nsample=nobs)
def ar1_sim_mat(nobs:int, ar1:NDArray[np.float64]):
""" return a matrix each of whose columns follow an AR(1) process """
ncol = len(ar1)
xmat = np.zeros(shape=[nobs, ncol])
for icol in range(ncol):
xmat[:, icol] = ar1_sim(nobs, ar1[icol])
return xmat
mypy statsmodels_util.py
says
statsmodels_util.py:5: error: Skipping analyzing "statsmodels.tsa.arima_process": module is installed, but missing library stubs or py.typed marker [import]
statsmodels_util.py:5: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
statsmodels_util.py:15: error: "ndarray" expects 2 type arguments, but 1 given [type-arg]
Found 2 errors in 1 file (checked 1 source file)
Mypy does accept a declaration of the form
def ar1_sim_mat(nobs:int, ar1:NDArray):
which leaves the rank of argument ar1
unspecified. My general question is how close can you get to Fortran’s type checking, which considers type, kind and rank, in Python. If the answer is “not close”, that is an argument for Fortran for some kinds of programs.