Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to set up mypy strict mode in Python
Demonstrates how to configure and run mypy in strict mode to enforce full type annotation coverage across a Python project.
from typing import Dict, Optional
def describe_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
"""Build a user description dictionary with strict type annotations."""
user: Dict[str, object] = {"name": name, "age": age}
if email is not None:
user["email"] = email
…
How to Use TypedDict for Data Validation in Python
Define a TypedDict schema and validate raw dictionary input with type hints for safer, more readable data handling.
from typing import Any, Dict, List, Optional, Union, TypedDict, Literal
class Product(TypedDict):
product_id: int
name: str
price: Union[int, float]
in_stock: bool
tags: Optional[List[str]]
def validate_product(data: Dict[str, Any]) -> Product:
product_id: int = int(data["product_id"])
na…
How to Validate Data in Python with Typing Hints
Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.
from typing import Any, Optional, Union, TypeVar, get_origin, get_args
T = TypeVar("T")
def validate(value: Any, expected_type: type) -> Optional[str]:
"""Returns an error message if value doesn't match expected_type, else None."""
# Handle Optional[...] types
origin = get_origin(expected_type)
if or…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.