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.



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

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

class Boat:
    status: BoatStatus

# 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))