Optional
💡 Means a value can exist OR be None
Example:
from typing import Optional
def find_friend(name: str) -> Optional[str]:
if name == "Abhi":
return "Best Friend"
return None
📦 Think of it like a box:
🎁 Sometimes it has a gift (a string).
🚫 Sometimes it’s empty (None
).
👉 Optional[str]
= "string OR nothing"
cast
💡 Means “I promise, this is of a certain type — trust me!”
Example:
from typing import cast
value = "123"
# Tell Python tools: “this is a string”
number_str = cast(str, value)
print(number_str.upper()) # ✅ Treated as string
🎭 At runtime: cast
does nothing magical
🎨 For type checkers: It’s like putting a label on an item.
👉 cast(str, value)
= “This is definitely a str
.”
🟢 Optional → “This gift box might have 🎸 or might be empty 🚫.”
🔵 cast → “This gift box is definitely 🎸 guitar, even if the label is wrong.”
✨ Summary
✅ Optional
= “maybe something, maybe nothing”
✅ cast
= “trust me, it’s this type”