Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optional Callable type hint in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading