*Memo:
- My post explains type hints (2).
- My post explains type hints (3).
- My post explains type hints (4).
- My post explains type hints (5).
- My post explains type hints (6).
- My post explains type hints (7).
A type hint:
- is the optional annotation(label) with the type created by one or more types for a variable, or function parameter or return value:
- A single type is considered as a non-union type.
- Multiple types are considered as a union type.
- can be done with
':', with one or more types and with or without'|'and'[]'. - is for the (static) type checkers such as mypy, pyright, pyre-check, pytype, etc so error doesn't occur with
python test.pyeven if a type hint is wrong.
Basically, I used mypy --strict for the experiments.
mypy --strict for the experiments. *mypy can be installed with pip install mypy.
A type hint can be done with ':', with one or more types and with or without '|' and '[]' as shown below:
*Memo:
-
'|':- can be used from Python 3.10.
- is Union which is an old way but can still be used:
-
UnionType is the alias of
Unionfrom Python 3.14 but currently, mypy gives error as the issue. - To set one or more types and
None, Optional can also be used from Python 3.10: - For
Union,UnionTypeandOptional:- The 1st arguments are
*types(Required:-Type:Type): - It's one or more types.
- Don't use any keywords like *types=, types=, etc.
-
str | int | None,Union[str, int, None]andOptional[str | int]are equivalent.
- The 1st arguments are
- The type of a single type is the non-union type which isn't
Unioneven if usingUnion,UnionTypeandOptional. - The type of multiple types is the union type which is
Unioneven if usingUnionTypeandOptional.
-
UnionType is the alias of
-
'[]':- can be used for iterables(a list, tuple, set, etc),
Union,UnionType,Optional, Callable(a function, generator or method), etc. - is required with
--strictbut optional without--strict.
- can be used for iterables(a list, tuple, set, etc),
# from typing import Union
v: str = 'Hello'
# v: Union[str] = 'Hello'
# Equivalent
v = 23
v = None
# Error
# from typing import Union, Optional
v: str | int | None = 'Hello'
# v: Optional[str | int] = 'Hello'
# v: Union[str, int, None] = 'Hello'
# Equivalent
v = 23
v = None
# No error
v = 2.3
# Error
# from typing import Union
v: list[int | str] = [0, 'A', 1, 'B', 2]
# v: Union[list[Union[int, str]]] = [0, 'A', 1, 'B', 2]
# Equivalent
v.append('C')
# No error
v.append(3.4)
v = {0, 1, 2}
# Error
# from typing import Union, Optional
def func(name: str, age: int | None = None) -> str | None:
# def func(name: str, age: Optional[int] = None) -> str:
# def func(name: Union[str], age: Union[int, None] = None) -> Union[str]:
return f'Name:{name}, Age:{age}' # Equivalent
print(func('John')) # No error
print(func(name='John')) # No error
print(func('John', 28)) # No error
print(func(name='John', age=28)) # No error
from typing import Any, Union, Optional
# The type of single type
print(type(int)) # <class 'type'>
print(type(None)) # <class 'NoneType'>
print(type(Any)) # <class 'typing._AnyMeta'>
print(type(Union[int])) # <class 'type'>
print(type(Optional[None])) # <class 'type'>
# The type of multiple types
print(type(int | float)) # <class 'typing.Union'>
print(type(None | Any)) # <class 'typing.Union'>
print(type(Union[int, float])) # <class 'typing.Union'>
print(type(Optional[int])) # <class 'typing.Union'>
Running python test.py, error doesn't occur with a wrong type hint as shown below:
v: int | list[float] = 'Hello'
# No error
print(v)
# Hello
Any and object can be used to accept all types as shown below:
*Memo:
-
Anyandobjectshouldn't be used because it's too general and almost all the operations ofobjectaren't supported by type checkers.
<Any>:
from typing import Any
v: Any = 'Hello'
def func(x: Any = None) -> Any:
pass
from typing import Any
v: Any = 'Hello'
print(v[2]) # No error
print(v.upper()) # No error
print(v + ' World') # No error
<object>:
v: object = 'Hello'
def func(x: object = None) -> object:
pass
v: object = 'Hello'
print(v[2]) # Error
print(v.upper()) # Error
print(v + ' World') # Error
Top comments (0)