Typing Function When Decorator Change Return Type
how to correctly write types for the function whose return type is modified by decorator ? Simple example: def example_decorator(fn): def wrapper(data): res = fn(data)
Solution 1:
May be a typechecker problem. Solution below. With mypy its ok but pycharm and pyre-check is complaining.
from typing import *
def example_decorator(
fn: Callable[[List[str]], List[str]]
) -> Callable[[List[str]], str]:
def wrapper(data: List[str]) -> str:
res = fn(data)
return ', '.join(res)
return wrapper
@example_decorator
def func(data: List[str]) -> List[str]:
data.append('XYZ')
return data
def test() -> str:
result = func(['ABC', 'EFG'])
print(type(result)) # <class 'str'>
return result
test()
Solution 2:
The function returns a list, so like this:
@example_decorator
def func(data: list) -> list:
new_data = data
new_data.append('XYZ')
return new_data
Post a Comment for "Typing Function When Decorator Change Return Type"