Back
+15 XP
Concept

Runtime Type Inspection with get_type_hints

`typing.get_type_hints(fn)` resolves stringified and forward-referenced type annotations into real Python class objects at runtime 🔍.

python
from typing import get_type_hints

def register_user(user_id: int, tags: list[str]) -> bool:
    return True

hints = get_type_hints(register_user)
print(hints)
# {'user_id': <class 'int'>, 'tags': list[str], 'return': <class 'bool'>} 🔍

# 99. Runtime Type Inspection with get_type_hints `typing.get_type_hints(fn)` resolves stringified and forward-referenced type annotations into real Python class objects at runtime 🔍. ```python from typing import get_type_hints def register_user(user_id: int, tags: list[str]) -> bool: return True hints = get_type_hints(register_user) print(hints) # {'user_id': <class 'int'>, 'tags': list[str], 'return': <class 'bool'>} 🔍 ``` Always use `get_type_hints()` instead of raw `fn.__annotations__`. Raw annotations may contain unresolved strings when `from __future__ import annotations` is active! 🔍 --- ### Question Why is `get_type_hints()` preferred over reading `fn.__annotations__` directly? 🧠 - [ ] a. It resolves forward-references and stringified type hints into actual type objects 🔍 - [ ] b. It verifies that function argument values are physically present in RAM - [ ] c. It turns off bytecode optimizations for the function - [ ] d. It automatically casts function arguments to strings --- ### Challenge Import `get_type_hints`. Define `def check(status: str) -> int: return len(status)`. Use `get_type_hints(check)` and print whether `hints['return'] is int`. 🎯 <details> <summary>Solution</summary> ```python from typing import get_type_hints def check(status: str) -> int: return len(status) hints = get_type_hints(check) print(hints["return"] is int) ``` </details>

Checkpoint

Why is `get_type_hints()` preferred over reading `fn.__annotations__` directly? 🧠

Practice

Import `get_type_hints`. Define `def check(status: str) -> int: return len(status)`. Use `get_type_hints(check)` and print whether `hints['return'] is int`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks