cast tells the type checker to treat a value as a specific type.
1from typing import cast23data = get_data() # type: Any45# Without cast — type checker warns6name = data["name"] # Warning: Key "name" not known78# With cast — type checker trusts you9from typing import TypedDict1011class UserData(TypedDict):12 name: str13 age: int1415user = cast(UserData, data)16print(user["name"]) # No warning!1718# With FastAPI19from fastapi import Request2021async def get_current_user(request: Request):22 user = request.state.user23 return cast(User, user) # Type checker knows it's User2425# Runtime: cast is just identity function26value = cast(int, "hello") # Returns "hello" unchanged!27print(type(value)) # <class 'str'>
When to use: