Type Hints - How to Use typing.cast() in Python


Python tip:

You can use cast() to signal to a type checker that the value has a designated type.

https://docs.python.org/3/library/typing.html#typing.cast

👇

from dataclasses import dataclass
from enum import Enum
from typing import cast


class BoatStatus(int, Enum):
    RESERVED = 1
    FREE = 2


@dataclass
class Boat:
    status: BoatStatus


Boat(status=2)
# example.py:16: error: Argument "status" to "Boat" has incompatible type "int"; expected "BoatStatus"
# Found 1 error in 1 file (checked 1 source file)

Boat(status=cast(BoatStatus, 2))