I want to use Type Hints in my Python program. How can I create Type Hints for complex data structures like
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
Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.
Python is a dynamically-typed language, which means that we don't have to specify data types when we create variables and functions. While this reduces the amount of code we need to write, the workload that we save is in turn added to the next developer that needs to understand and debug the existing function!
Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.
Typing defines a standard notation for Python function and variable type annotations. The notation can be used for documenting code in a concise, standard format, and it has been designed to also be used by static and runtime type checkers, static analyzers, IDEs and other tools.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With