I want to use Type Hints in my Python program. How can I create Type Hints for complex data structures like
Use the typing module; it contains generics, type objects you can use to specify containers with constraints on their contents:
import typing
def names() -> typing.List[str]: # list object with strings
return ['Amelie', 'John', 'Carmen']
def numbers() -> typing.Iterator[int]: # iterator yielding integers
for num in range(100):
yield num
Depending on how you design your code and how you want to use the return value of names()
, you could also use the types.Sequence and types.MutableSequence types here, depending on wether or not you expect to be able to mutate the result.
A generator is a specific type of iterator, so typing.Iterator
is appropriate here. If your generator also accepts send()
values and uses return
to set a StopIteration
value, you can use the typing.Generator object too:
def filtered_numbers(filter) -> typing.Generator[int, int, float]:
# contrived generator that filters numbers; returns percentage filtered.
# first send a limit!
matched = 0
limit = yield
yield # one more yield to pause after sending
for num in range(limit):
if filter(num):
yield num
matched += 1
return (matched / limit) * 100
If you are new to type hinting, then PEP 483 – The Theory of Type Hints may be helpful.