Back
+15 XP
Concept

Modern Union Operator X | Y (Python 3.10+)

Python 3.10+ introduced the pipe operator `|` for union types, deprecating verbose `Union[X, Y]` and `Optional[X]` imports ⚡.

python
def format_data(value: int | str | None) -> str:
    if value is None:
        return "N/A"
    return f"Val: {value}"

print(format_data(42))    # 'Val: 42' ⚡
print(format_data(None))  # 'N/A' ⚡

# 98. Modern Union Operator X | Y (Python 3.10+) Python 3.10+ introduced the pipe operator `|` for union types, deprecating verbose `Union[X, Y]` and `Optional[X]` imports ⚡. ```python def format_data(value: int | str | None) -> str: if value is None: return "N/A" return f"Val: {value}" print(format_data(42)) # 'Val: 42' ⚡ print(format_data(None)) # 'N/A' ⚡ ``` The `|` syntax also works in `isinstance(x, int | str)`, eliminating awkward tuple syntax like `isinstance(x, (int, str))`! ⚡ --- ### Question Which modern syntax replaces `Optional[int]` in Python 3.10+? 🧠 - [ ] a. `int | None` ⚡ - [ ] b. `int or None` - [ ] c. `?int` - [ ] d. `Nullable<int>` --- ### Challenge Write `def normalize(val: int | str) -> str: return str(val)`. Print `normalize(999)` and `normalize('test')`. 🎯 <details> <summary>Solution</summary> ```python def normalize(val: int | str) -> str: return str(val) print(normalize(999)) print(normalize("test")) ``` </details>

Checkpoint

Which modern syntax replaces `Optional[int]` in Python 3.10+? 🧠

Practice

Write `def normalize(val: int | str) -> str: return str(val)`. Print `normalize(999)` and `normalize('test')`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks