I have a function.
JavaScript
x
3
1
def func(num: int, item: str) -> list:
2
pass
3
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:
JavaScript
1
21
21
1
import typing
2
from typing import Callable
3
4
5
def func(num: int, item: str) -> list:
6
pass
7
8
9
def func_bad(num, item):
10
pass
11
12
13
def test_has_annotation(f: Callable) -> bool:
14
hints = typing.get_type_hints(f)
15
print(hints) # to check what this returns
16
return bool(hints)
17
18
19
print(test_has_annotation(func))
20
print(test_has_annotation(func_bad))
21
Result:
JavaScript
1
5
1
{'num': <class 'int'>, 'item': <class 'str'>, 'return': <class 'list'>}
2
True
3
{}
4
False
5