If you are using a recent version of Python (which you should because Python 2 will be EOL in less than a year) than you can use type hinting with a sane syntax instead of using docstrings to document the arguments types.
For those of you that are not yet sold on static typing, especially in a dynamic language, I will post a separate post about it in the future. You could come back to this post when you decide to embrace static typing.
The type of a variable comes after the name of the variable, separated with a colon. The syntax for variable type hinting and argument type hinting is the same.
To indicate the return type of a function, you need to put an arrow (->) followed by the type and a colon like any other function. Here is an example of a function with type hinting for the argument and return value:
def greeting(name: str) -> str:
return 'Hello ' + name
You can use all the built in types for type hinting but they are kind of limiting. You can’t specify a more abstract types like iterable or a more specific type like a list of strings.
There are more advance types in the typing package that can let you
create more precise function signatures. Instead of using
list, you can
typing.List and specify the list type in brackets if you want
to. For example if we would want to greet multiple people our function
could look like this:
from typing import List
def multiple_greetings(names: List[str]) -> List[str]:
return list(map(greeting, names))
There are also abstract types that doesn’t map to a specific
implementation but instead represent an interface that more than one
type implement. A few of those that I find useful are
typing.Mapping. With those types we could redefine our
multiple_greetings functions like this:
from typing import Iterable, Iterator
def multiple_greetings(names: Iterable[str]) -> Iterator[str]:
return map(greeting, names)
Python doesn’t check the types on his own, the interpreter only add it
__annotations__ property. If you want to validate your program
using the type hinting you just added you will need another tool. If you
are using an IDE like PyCharm you will have type checking built in
without installing anything else. If you are using an editor or want a
better type checker than PyCharm I recommend mypy.
You can install mypy through pip with the command
python3 -m pip install -U mypy
After the installation is complete you can simply run mypy from the terminal with your package directory as an argument and you will get a list of complaints about your typing.
This post should help you start adding type hinting to your code but you might still feel a little bit limited with using only the existing types in the typing package. There are more advance way of defining new types that I will cover in a future post.
If you can’t wait for my second post, you can learn more about typing from the official typing documentation.