We want to use static type checking and type annotations in our Python code for detecting errors we made. We will use the mypy extension in VS code for that.
Why we got type hints according PEP 484 -- Type Hints (29-Sep-2014):
> [Rationale and Goals](https://www.python.org/dev/peps/pep-0484/#id11)
>
> This PEP aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.
>
> Of these goals, static analysis is the most important. This includes support for off-line type checkers such as mypy, as well as providing a standard notation that can be used by IDEs for code completion and refactoring.
>
> [...]
>
> It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.
I would redefine this list a bit:
* It is a part of your automatic documentation (like with meaningful variable names). If another person gets your source code they understand it easier.
* You editor might thank you. Do to some new features in Python 3.10, the modern editors that do syntax highlighting and error checking have a harder time to infer what you mean. The more it need to think about what you mean, the slower your editor might get or even fail to show you syntax highlighting.
* Static code analysis is really helpful. It showed me any problems ahead that I would have figured out the hard way otherwise.
* Packages like the just-in-time compiler numba can produce better results if you can tell it what the variables are.
## How do we do it?
Variables are assigned to a type the ***first*** time when used or can be defined even before use:
You are allowed to connect a variable ***once and only once*** to a type. If you assign a type a second time to a variable then you will get an error and have to remove the second assignment.
For functions it looks a bit different because we have to handle the type of the return value with the **->** construct:
```python
def this_is_a_function() -> None:
pass
def this_is_a_function() -> int:
return 5
def this_is_a_function(a: int) -> int:
return a
def this_is_a_function(a: int, b: int = 8) -> int:
return a + b
def this_is_a_function(a: int, b: int = 8) -> tuple[int, int]:
Please note, that there is a difference how type annotations worked for older version. I will cover only Python 3.10 and newer. The official documentation can be found [here](https://docs.python.org/3/library/typing.html).
* If the type starts with an upper letter then you might import it from the typing module like
```python
from typing import Any
```
* If you have no clue what type something has, well use **type()**:
```python
import numpy as np
import torch
def func() -> None:
return
a = 0
b = np.zeros((10,))
c = torch.zeros((10, 1))
d = func
print(type(a))
print(type(b))
print(type(c))
print(type(d))
```
Output:
```python
<class'int'>
<class'numpy.ndarray'>
<class'torch.Tensor'>
<class'function'>
```
The correct typing would have been:
```python
import numpy as np
import torch
from typing import Callable
def func() -> None:
return
a: int = 0
b: np.ndarray = np.zeros((10,))
c: torch.Tensor = torch.zeros((10, 1))
d: Callable = func
```
As you can see, we had to change **b** a bit because we didn't use **import numpy** but used **import numpy as np**. Thus we had to use **np.ndarray** instead of **numpy.ndarray**.
Concerning **<class'function'>**, this is a specical case. And requires an import from the typing module via **from typing import Callable**. More about that later.
In the case you expect a variable that can have differnt types over it's lifetime. Let us say you initialize it with None and later want to store integer in it:
This is called a [Union](https://docs.python.org/3/library/typing.html#typing.Union). The Union with **None** is called [Optional](https://docs.python.org/3/library/typing.html#typing.Optional). But nowadays you just need to remember **\|**.
a = np.zeros((10, 1)) # -> Incompatible types in assignment (expression has type "ndarray[Any, dtype[floating[_64Bit]]]", variable has type "ndarray[Any, dtype[unsignedinteger[_64Bit]]]")
Callable means "function". As you know, you can shove functions objects around and also use then as function arguments of other function. It is helpful to make sure that the function you get has the properties you expect.
|NewType | Use the NewType helper to create distinct types|
|Generics| Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements. |
|User-defined generic types|A user-defined class can be defined as a generic class.|