I want to use Type Hints in my Python program. How can I create Type Hints for complex data structures like
- lists with strings
- a generator returning integers?
Example
def names() -> list:
# I would like to specify that the list contains strings?
return ['Amelie', 'John', 'Carmen']
def numbers():
# Which type should I specify for `numbers()`?
for num in range(100):
yield num
Use the
typing
module; it contains generics, type objects you can use to specify containers with constraints on their contents:Depending on how you design your code and how you want to use the return value of
names()
, you could also use thetypes.Sequence
andtypes.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 acceptssend()
values and usesreturn
to set aStopIteration
value, you can use thetyping.Generator
object too:If you are new to type hinting, then PEP 483 – The Theory of Type Hints may be helpful.