Verified Commit 1b90e6e7 authored by Renato Alves's avatar Renato Alves 🌱
Browse files

Add session 06 on type hints

parent 7bc830ab
# Type hints
Type hints are an optional feature introduced in Python 3.5 and
described in [a multitude of PEPs](https://docs.python.org/3/library/typing.html).
They allow specifying the type of inputs, outputs and variables
and can be used by a miriad of tools to help you check if the
code is self consistent, provide contextual auto-completion,
among other benefits.
## Static type analysers
Static type analysers ensure that the type of different parts
of the code match on which types they expect.
Since types are explicitly stated, IDEs can also use this
information to provide contextual auto-completion.
There are several tools that provide this feature. The three
most well known are:
* [mypy](http://mypy-lang.org/), community developed, first on scene and widely used.
* [pytype](https://github.com/google/pytype) developed at Google (but not officially supported).
* [pyright](https://github.com/microsoft/pyright) officially supported by Microsoft (written in JavaScript)
All of them provide static code inspection with some differences
in features and how you interact with it.
## .pyi stub files
Static analysis tools can often also use and in some cases generate
.pyi files (specified in [PEP 561](https://www.python.org/dev/peps/pep-0561))
that contain the type hints.
If you are familiar with C languages, they can be seen as the *header* files,
providing only the signatures of functions, classes and variables.
Since type hints are still a relatively new feature and not all libraries
are using it, the python community has setup repositories such as
[typeshed](https://github.com/python/typeshed) to provide stub files for
commonly used libraries. These are in turn used by static analysers
such as **mypy** to improve type checking and code inspection.
## Common types
* int
* str
* bytes
* float
* tuple
* list
#!/usr/bin/env sh
python3.9 -m venv helpers/venv
source helpers/venv/bin/activate
pip install -r helpers/requirements.txt
# -*- coding: utf-8 -*-
# Needed for Python >=3.7 <3.10
from __future__ import annotations
# Types to explore:
# int, str
# list, dict, tuple, set
# class
# typing.Any
# typing.Union
# typing.Optional
# typing.NewType (aka alias)
# collections.abc.*
# def multiply(var: annot = default) -> returnval:
def main():
pass
if __name__ == "__main__":
main()
#!/usr/bin/env sh
set -e
if [ ! -f helpers/venv/bin/activate ]; then
./helpers/make_venv.sh
fi
source helpers/venv/bin/activate
mypy sample.py
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment