I have a function.
def func(num: int, item: str) -> list: pass
And I want to add a test that checks that function and parameters have a type annotation. It is needed by other developers don’t change input and output types.
Any idea how to do that? I want to use pytest, maybe mocks?
Advertisement
Answer
You can use the get_type_hints function from typing:
import typing
from typing import Callable
def func(num: int, item: str) -> list:
    pass
def func_bad(num, item):
    pass
def test_has_annotation(f: Callable) -> bool:
    hints = typing.get_type_hints(f)
    print(hints)  # to check what this returns
    return bool(hints)
print(test_has_annotation(func))
print(test_has_annotation(func_bad))
Result:
{'num': <class 'int'>, 'item': <class 'str'>, 'return': <class 'list'>}
True
{}
False
