I am starting to experiment with type hints in python and I am having some problems with types of optional callables.
It will probably be very simple to solve, however I am not sure how to do it.
For example, the function I attach in the question.
from typing import Callable, Optional
import numpy as np
def running_mean(
xx: np.ndarray,
yy: np.ndarray,
bins: np.ndarray,
kernel: Optional[Callable[[np.ndarray], np.ndarray]] = None,
) -> np.ndarray:
# if ther is no input kernel function fall to default (wich is a gausian kenrnel)
weight_func = kernel
if kernel is None:
_width = (xx.max() - xx.min()) / 10
weight_func = lambda x: np.exp(-((x) ** 2) / (2 * _width**2)) * (
np.abs(x / _width) < 2
)
smoothed = np.array([np.average(yy, weights=weight_func(xx - x)) for x in bins])
return smoothed
With this function I want to do a running mean of some input data.
The weights for the running mean are computed via the kernel function.
I want this function to be optional, so if the user does not provide anything, it will use a gaussian kernel.
However, my IDE (Visual Studio Code), highlights this line:
smoothed = np.array([np.average(yy, weights=weight_func(xx - x)) for x in bins])
with this error:
Object of type "None" cannot be calledPylance(reportOptionalCall)
(variable) weight_func: ((x: Unknown) -> Any) | ((ndarray) -> ndarray) | None
My question is: how can I indicate that <weight_func> cannot be None type anymore?
Any advise is welcome!
>Solution :
Don’t set it to None in the first place:
if kernel is not None:
weight_func = kernel
else:
# construct default fallback weight_func