Modern Python Type Annotations & typing
Type annotations clarify function contracts without runtime overhead. Use `Union`, `Optional`, and type aliases to catch bugs at compile-time with static checkers like Mypy 🏷️.
from typing import Optional, Union, List
def format_id(user_id: Union[int, str], prefix: Optional[str] = None) -> str:
clean_id = str(user_id)
return f"{prefix}_{clean_id}" if prefix else clean_id
print(format_id(42)) # '42' 🏷️
print(format_id("adm", "USR")) # 'USR_adm' 🚀
# 90. Modern Python Type Annotations & typing Type annotations clarify function contracts without runtime overhead. Use `Union`, `Optional`, and type aliases to catch bugs at compile-time with static checkers like Mypy 🏷️. ```python from typing import Optional, Union, List def format_id(user_id: Union[int, str], prefix: Optional[str] = None) -> str: clean_id = str(user_id) return f"{prefix}_{clean_id}" if prefix else clean_id print(format_id(42)) # '42' 🏷️ print(format_id("adm", "USR")) # 'USR_adm' 🚀 ``` Remember: Python type annotations are strictly advisory at runtime — CPython does NOT throw TypeErrors if arguments mismatch. They exist for static linters and IDE tooling! 🏷️ --- ### Question What does CPython do at runtime if you pass an integer into a function annotated with `name: str`? 🧠 - [ ] a. Executes normally without raising an error (type hints have zero runtime enforcement) 🏷️ - [ ] b. Raises an immediate TypeError - [ ] c. Casts the integer to a string automatically - [ ] d. Terminates the program with exit code 1 --- ### Challenge Write `greet_user(name: Optional[str]) -> str` returning `f'Hello, {name}'` if `name` is provided else `'Hello, Guest'`. Print `greet_user('Alex')` and `greet_user(None)`. 🎯 <details> <summary>Solution</summary> ```python from typing import Optional def greet_user(name: Optional[str]) -> str: return f"Hello, {name}" if name else "Hello, Guest" print(greet_user("Alex")) print(greet_user(None)) ``` </details>