On this page
typing.cast
Prev: typing.Callable | Up: typing | Next: typing.ChainMap
Rel: typing.AbstractSet, typing.Annotated, typing.Any, typing.assert_never
Ref: docs.python.org — typing.cast
Tags: #public #python3 #stdlib #typing
Import
import typing
from typing import cast
Signature & Overview
typing.cast(typ, val)
Cast a value to a type.
Usage
from typing import cast
raw: object = "hello"
text = cast(str, raw)
assert text == "hello"
Gotchas
- Zero runtime conversion or validation:
cast(int, "not an int")returns"not an int"untouched—useisinstance()orint(...)when you need runtime safety.
REPL Inspect
from typing import cast
help(cast)
Linked from
Related notes
- tuts/python3/stdlib_module/typing/Callable Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/ChainMap Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/AbstractSet Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Annotated Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Any Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_never Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_type shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncContextManager shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncGenerator shared tags: #stdlib, #typing