Annotations for decorator

Viewed 198

I am struggling with annotating a decorator function.
When executing mypy --strict . mypy complains: test.py:25: error: Untyped decorator makes function "func1" untyped.
As far as I can see my decorator is not untyped...
What I could change is the annotations of the decorator, I cannot change the concept behind how objects are generated (classes Generator and Test), or how the parameters are passed (instantiation).

from typing import Dict, Any, List
import functools


def has_params(params: Dict[str, Any]) -> Any:
    def param_decorator(func: Any) -> Any:
        @functools.wraps(func)
        def func_decorator(*args: Any) -> Any:
            class_obj = args[0]
            for param in params:
                if (param not in class_obj.params.keys()):
                    raise Exception(f'Parameter {param} not passed to object, but required by function {class_obj.name}.{func.__name__}')
                if (not isinstance(class_obj.params[param], params[param])):
                    raise Exception(f'Parameter {param} for object {class_obj.name} has the wrong type, expected {params[param]}, got {type(class_obj.params[param])}')
            return func(*args)
        return func_decorator
    return param_decorator


class Test():
    def __init__(self) -> None:
        self.__params: Dict[str, Any] = dict()
        self.__name = "Test"

    @has_params(params={'param1': bool})
    def func1(self) -> None:
        # self.params['param1'] can be safely accessed here because it is type checked by @has_params
        print(f'Got param1: {self.params["param1"]}')

    @property
    def params(self) -> Dict[str, Any]:
        return self.__params
    @params.setter
    def params(self, value: Dict[str, Any]) -> None:
        self.__params = value
    @property
    def name(self) -> str:
        return self.__name


class Generator():
    def __init__(self) -> None:
        self.__obj_list: List[Test] = list()

    def add_elem(self, name: str, params: Dict[str, Any] = {}) -> None:
        obj = self._create_object_by_name(name)
        obj.params = params
        self.__obj_list.append(obj)

    def execute(self) -> None:
        for obj in self.__obj_list:
            obj.func1()

    def _create_object_by_name(self, class_name: str) -> Any:
        if class_name in globals():
            return globals()[class_name]()
        else:
            raise Exception(f'Class "{class_name}" is not defined')


gen = Generator()
gen.add_elem('Test', params={'param1': 7.5})
gen.execute()
1 Answers

I believe the problem is that the annotations on your decorator return Any, when really it should return a Callable. If you change the return type of has_params and especially of param_decorator to Callable[..., Any] it works.

Or better still, declare a type variable with an upper-bound on arbitrary callables:

F = TypeVar('F', bound=Callable[..., Any])

And annotate

def param_decorator(func: F) -> F: ...

Update: When testing this out myself, I also had to add:

    return cast(F, func_decorator)

at the end of param_decorator or else mypy complained

Incompatible return value type (got "Callable[[VarArg(Any)], Any]", expected "F")

I'm not sure if there's a better way to handle generic function wrapping, though this seems consistent with what the mypy documentation suggests.

See also https://mypy.readthedocs.io/en/stable/generics.html#declaring-decorators

Related