- Type hints are optional
-
The type
Anyis used when the type is not assign - It does not improve performance
-
mypyis one of the tool used to static check
[mypy]
python_version = 3.9
warn_unused_configs = True
disallow_incomplete_defs = True-
Below a type hint for a function
-
Use one space after
:and one space between two sides=
-
Use one space after
def show_count(count: int, singular: str, plural: str = '') -> str:
if count == 1:
return f'1 {singular}'
count_str = str(count) if count else 'no'
if not plural:
plural = singular + 's'
return f'{count_str} {plural}'-
We can use
Noneas default value for parameterdef show_count(count: int, singular: str, plural: Optional[str] = None) -> str: -
Use
OptionalwithNone -
Import types using
from typing import Xto decrease function signs - Duck Typing and Nominal Typing are two types used in Python
-
The type
Anyaccepts anything -
General types have interface more restricts, which is, they support less operations.
objectimplements less operations thanabc.Sequence, which implements implements less operations thanabc.MutableSequence, which in turn implement less operations thanlist - Liskov Substitution
-
Unionmeansor-
Union[str, None]: means that parameter or variable can bestrorNone
-
-
Generic collections:
container[item]like we have forlist[str] -
Tuple: records and immutable list as register/records use types inside
[]-
tuple as immutable list use type with
ellipsistuple[int,...]
-
tuple as immutable list use type with
- NamedTuple: Works like classes
- dict:
def name_index(start: int = 32, end: int = STOP_CODE) -> dict[str, set[str]]:
index: dict[str, set[str]] = {} # (2)
for char in (chr(i) for i in range(start, end)):
if name := unicodedata.name(char, ''): # (3)
for word in tokenize(name):
index.setdefault(word, set()).add(char)
return index-
It is better to use to use
abc.MutableMappingorabc.Mappingfor type hints-
dictis brother ofUserDict
-
-
Use
listfor returning andIterableandSequencefor parameters
from collections.abc import Iterable
FromTo = tuple[str, str] # (1)
def zip_replace(text: str, changes: Iterable[FromTo]) -> str: # (2)
for from_, to in changes:
text = text.replace(from_, to)
return text-
Callableis used to type callable objects-
Callable[[ParamType1, ParamType2], ReturnType] - Example: Strategy using functions
-
sources
- fluent python - Luciano Ramalho - 2023 - Second Edition - Web Edition
-
[[]]❌