{"slug": "python-type-hints-cheat-sheet-for-working-developers", "title": "Python Type Hints Cheat Sheet for Working Developers", "summary": "A developer published a practical Python type hints cheat sheet covering scalar and collection annotations, function signatures with return types, and advanced patterns like Protocol for structural subtyping and TypedDict for structured JSON payloads. The guide recommends running mypy --strict in CI/CD pipelines and adopting modern built-in generics such as list[str] and str | None on Python 3.10+, with examples drawn from typing Anthropic SDK calls.", "body_md": "3 min read · 512 words\n\nPython’s type hinting system has evolved from a quiet PEP into an indispensable tool for growing codebases. If you are still writing raw Python without type hints, you are missing out on instant IDE feedback, bulletproof refactoring, and self-documenting code.\n\nLet's cut the theory. Here is a practical, no-fluff cheat sheet for the type hints you will actually use in production every day.\n\nKeep it simple. Scalars use standard Python types (`str`, `int`, `float`, `bool`), while collections require imports from the `typing` module or modern built-in generics (supported in Python 3.9+).\n\n``` python\nfrom typing import Dict, List, Optional, Tuple, Union\n\n# Scalars\nname: str = \"Claude\"\nage: int = 5\nis_active: bool = True\nprice: float = 99.9\n\n# Collections\ntags: List[str] = [\"ai\", \"llm\", \"python\"]\ncoordinates: Tuple[float, float] = (37.7749, -122.4194)\nmetadata: Dict[str, Union[str, int]] = {\"model\": \"claude-opus-5\", \"tokens\": 1000000}\n\n# Optional values (equivalent to Type | None)\nmiddle_name: Optional[str] = None\n```\n\nFunctions are where type hints shine brightest. Always type your arguments and your return values. Use `-> None` for functions that perform side effects without returning data.\n\n``` python\nfrom typing import Callable, Sequence\n\ndef calculate_cost(tokens: int, rate_per_million: float) -> float:\n    \"\"\"Calculate API cost based on token usage.\"\"\"\n    return (tokens / 1_000_000) * rate_per_million\n\ndef process_batch(items: Sequence[str], callback: Callable[[str], None]) -> None:\n    \"\"\"Process a sequence of items and execute a callback on each.\"\"\"\n    for item in items:\n        callback(item)\n\n# Real-world usage with the modern Anthropic SDK\nimport anthropic\n\ndef generate_completion(prompt: str, model_id: str = \"claude-opus-5\") -> str:\n    client = anthropic.Anthropic()\n    response = client.messages.create(\n        model=model_id,\n        max_tokens=4000,\n        messages=[{\"role\": \"user\", \"content\": prompt}],\n    )\n    # Extract text from the response content blocks safely\n    return \"\".join(block.text for block in response.content if block.type == \"text\")\n```\n\nWhen your codebase grows, strict class hierarchies can slow you down. Use `Protocol` for structural subtyping (duck typing with type safety) and `TypedDict` for structured JSON payloads.\n\n``` python\nfrom typing import Protocol, TypedDict\n\n# Protocol: Any object with a 'generate' method matches this type\nclass LLMProvider(Protocol):\n    def generate(self, prompt: str) -> str:\n        ...\n\n# TypedDict: Perfect for validating API payloads and config dictionaries\nclass APIConfig(TypedDict):\n    model: str\n    max_tokens: int\n    thinking_enabled: bool\n\ndef configure_request(config: APIConfig) -> None:\n    print(f\"Configuring request for model: {config['model']}\")\n\n# Valid dictionary matching TypedDict structure\nmy_config: APIConfig = {\n    \"model\": \"claude-sonnet-5\",\n    \"max_tokens\": 8000,\n    \"thinking_enabled\": True\n}\n\nconfigure_request(my_config)\n```\n\n`mypy --strict your_module.py` to your CI/CD pipeline to catch type errors before they hit production.`list[str]` over `List[str]` and `str | None` over `Optional[str]` if you are running Python 3.10+.`Any` temporarily—just don't leave it there permanently.\nWhat is your favorite advanced typing pattern in Python? Drop a comment below with your go-to trick or headache. If you found this cheat sheet helpful, hit the bookmark button and share it with your team!", "url": "https://wpnews.pro/news/python-type-hints-cheat-sheet-for-working-developers", "canonical_source": "https://dev.to/syncore/python-type-hints-cheat-sheet-for-working-developers-40le", "published_at": "2026-10-19 16:38:50+00:00", "updated_at": "2026-10-19 16:44:35.508196+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Python", "Anthropic", "mypy"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/python-type-hints-cheat-sheet-for-working-developers", "markdown": "https://wpnews.pro/news/python-type-hints-cheat-sheet-for-working-developers.md", "text": "https://wpnews.pro/news/python-type-hints-cheat-sheet-for-working-developers.txt", "jsonld": "https://wpnews.pro/news/python-type-hints-cheat-sheet-for-working-developers.jsonld"}}