DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

Type hints in Python (1)

Buy Me a Coffee

*Memo:

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.py even if a type hint is wrong.

Basically, I used 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 Union from 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, UnionType and Optional:
        • 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] and Optional[str | int] are equivalent.
      • The type of a single type is the non-union type which isn't Union even if using Union, UnionType and Optional.
      • The type of multiple types is the union type which is Union even if using UnionType and Optional.
  • '[]':
    • can be used for iterables(a list, tuple, set, etc), Union, UnionType, Optional, Callable(a function, generator or method), etc.
    • is required with --strict but optional without --strict.
# from typing import Union

v: str = 'Hello'
# v: Union[str] = 'Hello'
# Equivalent

v = 23
v = None
# Error
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode
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'>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Any and object can be used to accept all types as shown below:

*Memo:

  • Any and object shouldn't be used because it's too general and almost all the operations of object aren't supported by type checkers.

<Any>:

from typing import Any

v: Any = 'Hello'

def func(x: Any = None) -> Any:
    pass
Enter fullscreen mode Exit fullscreen mode
from typing import Any

v: Any = 'Hello'

print(v[2])         # No error
print(v.upper())    # No error
print(v + ' World') # No error
Enter fullscreen mode Exit fullscreen mode

<object>:

v: object = 'Hello'

def func(x: object = None) -> object:
    pass
Enter fullscreen mode Exit fullscreen mode
v: object = 'Hello'

print(v[2])         # Error
print(v.upper())    # Error
print(v + ' World') # Error
Enter fullscreen mode Exit fullscreen mode

Top comments (0)