Back
+15 XP
Concept

Literal Types with typing.Literal

`typing.Literal` constrains a variable to specific exact values. It functions as a lightweight enum for string modes, HTTP methods, and status flags 🎯.

python
from typing import Literal

def set_mode(mode: Literal["r", "w", "a"]) -> str:
    return f"Mode configured: {mode}"

print(set_mode("r"))  # Allowed ✅
# set_mode("x")       # Flagged by type checker! 🛑

# 95. Literal Types with typing.Literal `typing.Literal` constrains a variable to specific exact values. It functions as a lightweight enum for string modes, HTTP methods, and status flags 🎯. ```python from typing import Literal def set_mode(mode: Literal["r", "w", "a"]) -> str: return f"Mode configured: {mode}" print(set_mode("r")) # Allowed ✅ # set_mode("x") # Flagged by type checker! 🛑 ``` Using `Literal['read', 'write']` provides instant IDE autocompletion for string arguments without needing to import full Enum classes! 🎯 --- ### Question What error prevention benefit does `mode: Literal['json', 'csv']` provide? 🧠 - [ ] a. Ensures only the exact strings 'json' or 'csv' can be passed without typo errors 🎯 - [ ] b. Converts invalid strings to binary automatically - [ ] c. Forces Python to create database tables for both strings - [ ] d. Disables string interpolation in the function body --- ### Challenge Import `Literal`. Define `def switch_theme(theme: Literal['dark', 'light']) -> str: return f'Theme is {theme}'`. Print `switch_theme('dark')`. 🎯 <details> <summary>Solution</summary> ```python from typing import Literal def switch_theme(theme: Literal["dark", "light"]) -> str: return f"Theme is {theme}" print(switch_theme("dark")) ``` </details>

Checkpoint

What error prevention benefit does `mode: Literal['json', 'csv']` provide? 🧠

Practice

Import `Literal`. Define `def switch_theme(theme: Literal['dark', 'light']) -> str: return f'Theme is {theme}'`. Print `switch_theme('dark')`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks