It has really been a while since last time I posted something on the blog. Let’s get the rhythm back again with this post.
I can understand the purpose of introducing Type Hints and
mypy: a static typing system to help the machine (in this case
, other static checkers and whatever tools, like IDE) to check the types of your code at compile time. This can help you spot certain
bugs earlier while building larger software system with Python. And in some ways, the type annotations might make your code easier
to understand. For example, see the following code:
And save it as
mypy-example.py, then if you run
mypy against this file:
Mypy actually helped you catch a bug here! However, I do have to say, since you need to add type hints in your code to make this work, it does add some overhead to development compared to traditional python programs.
Now, here are some of the tips I collected over using Type Hints and
Optionalfor values that could be
None(like often happens in keyword-only arguments).
- Generator is a function that yields a sequence; it is annotated as an
- When you are puzzled what type it is for a variable, put
reveal_type(var)in the code and run mypy; the type of
varwill be printed out on
stdout. Afterwards you can remove
# type: ignoreto suppress errors on a given line. This is used when your code confuses mypy (or mypy has a bug). You also see it used a lot to suppress missing imports.
- To specify a callable without telling its signature, use
Callable[..., int]. See PEP 0484.
- Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example
Tuple[int, ...]. The
...is part of the syntax. See PEP 0484 on
- User-defined classes are valid as types in annotations.
if TYPE_CHECKING:is used to avoid import cycles or an import is only needed for type annotations in forward references.
Side Note on
... is actually a valid Python expression which represents the singleton
It is originally from
numpy package for advanced slicing notation. But it is now also used as:
- A place holder for not-yet-written code.
- Specify type hints using
typingmodule (like what we saw above).
- As a default argument value, especially when you want to distinguish between not passing a value and passing in