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()