PEP 484: Type Hints was introduced in Python 3.5. For more information, see Official document type hint support (https://docs.python.org/en/3/library/typing.html).
Recently, I've heard a lot of stories that have been introduced in the community. I would like to introduce it in future projects as well, and I will summarize it here for reference when studying myself and explaining it to others.
Type hints were introduced in Python 3.5 and later as a Python grammar.
--Since it is a hint, it has no effect at runtime --There is no official built-in tool
--There is a de facto check tool called mypy (installable with pip) ――Editors such as PyCharm support it, code interpolation becomes powerful, and it also checks. --Valid only in the place where the hint is described (either module or function) ――The more hints you write, the more effective the code interpolation will be, and the more it will check.
install mypy
(env) $ pip install mypy
Check with mypy
(env) $mypy module name
As an example, all are shown as integer (int) type.
a: int = 10
a: int
a = 10
def f(a: int):
pass
def f(a: int = 10):
pass
def f(a) -> int:
return 10
def f(a: int, b: int = 10) -> int:
return a + b
name | Mold |
---|---|
integer | int |
Floating point number | float |
String | str |
Byte type | bytes |
Truth value | bool |
None | None |
Since the container system specifies the type to be included, I want to write it as list [int]
. However, this results in a Python syntax error. For that reason, typing prepares a dedicated mold.
from typing import List, Tuple, Dict, Set
name | Mold | Definition example |
---|---|---|
list | List | List[int] |
Tuple | Tuple | Tuple[int, int] / Tuple[int, ...] |
dictionary | Dict | Dict[str, int] |
set | Set | Set[int] |
from typing import Any
name | Mold | Definition example |
---|---|---|
Anything is fine | Any | Any |
from typing import Callable, Iterator, MutableMapping
name | Mold | Definition example |
---|---|---|
Callable | Callable | Callable[[int, float], bool] |
Repeatable | Iterator | Iterator[int] |
Behavior like a dictionary | MutableMapping | MutableMapping[str, int] |
Optional
Optional is a type that allows the specified type or None. For example, ʻOptional [int]` to allow either an integer or None.
It is used in the following cases.
from typing import Optional
def f1(a: int, b: int) -> Optional[int]:
if b == 0:
return None
return a // b
It is convenient because it can be used as follows.
def f2(c: Optional[int]) -> int:
if c is None:
c = 0
return c + 100
If you describe the above case as follows, mypy will notify you of the error.
def f2(c: Optional[int]) -> int:
return c + 100
$ mypy sample.py
sample.py:**: error: Unsupported operand types for + ("None" and "int")
sample.py:**: note: Left operand is of type "Optional[int]"
Found 1 error in 1 file (checked 1 source file)
That is, by doing ʻif c is None`, we add the time when c is None, so that in the subsequent lines, the variable c Is determined to be an integer type (int), so we guarantee that it can be processed without problems.
Union
Union can indicate one of two types. For example, when you say integer type or string type, specify ʻUnion [int, str]`.
When receiving an argument as shown below, it is used when you do not know whether it is an integer or a character string, and by dividing the process using ʻisinstance`, you can determine the variable type in the same way as Optional above. I can do it.
from typing import Union
def f3(d: Union[int, str]) -> str:
if not isinstance(d, str):
d = str(d)
return d.upper()
Here, as ʻif not is instance (d, str):, when the variable d is not a character string type (str), the process of converting to a character string is inserted and the process is continued. Since
return d.upper () knows that
d` is a string, we can use a string-type method to safely convert it to uppercase.
You cannot specify a float by specifying int, but you can specify an opposite float and insert an int. In the following cases, only num4 will give an error.
num1: float = 1.0
num2: float = 1
num3: int = 1
num4: int = 1.0 #This will result in an error
$ mypy sample/sample.py
sample.py:**: error: Incompatible types in assignment (expression has type "float", variable has type "int")
It seems that this is because int can be automatically converted to float, but if the opposite float is set to int, information may be lost.