Appearance
Typing and Modern Python
58. What are type hints, and how are they checked?
The short answer
Type hints annotate what a function expects and returns, def total(items: list[LineItem]) -> int:, and what variables hold. Python itself does not enforce them at runtime; they are read by static type checkers, such as mypy, Pyright, and newer fast Rust-based checkers such as Astral's ty, and by editors for autocomplete, and by libraries such as Pydantic and FastAPI, which use them at runtime to validate data. Add them to public functions and data models first; they catch whole classes of bugs before the code runs and document intent.
python
from decimal import Decimal
def apply_discount(price: Decimal, percent: int | None = None) -> Decimal: # (1)
if percent is None:
return price
return price * (100 - percent) / 100
apply_discount("10.00", 5) # (2) runs fine, but a type checker reports: str is not Decimalint | Nonemeans "an int or None", the modern spelling ofOptional[int], since 3.10.- Runtime does not check, so the bug only shows in the checker or later as wrong behaviour.
| Annotation | Meaning |
|---|---|
list[str], dict[str, int], tuple[int, str] | Built-in generics, since 3.9 |
int | None | Optional value |
Callable[[int], str] | A function from int to str |
Literal["paid", "refunded"] | Only these values |
Any | Opts out of checking; avoid |
Self | The current class, for fluent methods |
59. How do generics work in Python, including the 3.12 syntax?
The short answer
Generics let a function or class work with any type while keeping track of which one: first(items: list[T]) -> T tells the checker that a list of Order returns an Order. Since Python 3.12, you declare type parameters directly in brackets, def first[T](items: list[T]) -> T | None, and class Box[T]:, instead of creating TypeVar objects by hand. The type statement creates type aliases, type OrderId = int. You can bound parameters, [T: Number], or constrain them to a few types, [T: (int, float)].
python
def first[T](items: list[T]) -> T | None: # (1)
return items[0] if items else None
class Page[T]: # (2)
def __init__(self, items: list[T], next_cursor: str | None):
self.items = items
self.next_cursor = next_cursor
type OrderId = int # (3)
type JsonValue = str | int | float | bool | None | list[JsonValue] | dict[str, JsonValue] # (4)
print(first([3, 4]), first([])) # 3 None- A generic function: the return type follows the input's element type.
- A generic class:
Page[Order]andPage[Customer]are checked separately. - A type alias with the
typestatement. - Aliases can be recursive, which describes JSON exactly.
The older spelling, still common in libraries: T = TypeVar("T") and class Page(Generic[T]):.
60. What are TypedDict, Literal, Protocol and other useful typing tools?
The short answer
TypedDict describes a dict with known keys and value types, for JSON-like data that stays a plain dict. Literal restricts a value to specific constants, such as order statuses. Protocol describes a shape any class can match without inheriting (Protocols). @overload describes functions whose return type depends on the arguments. Final marks a constant, TypeGuard and TypeIs narrow types in custom checks, and Annotated attaches extra metadata, which FastAPI uses for parameters and dependencies.
python
from typing import TypedDict, Literal, NotRequired, Annotated
type Status = Literal["pending", "paid", "shipped", "refunded"]
class OrderIn(TypedDict):
sku: str
qty: int
note: NotRequired[str] # (1)
def set_status(order_id: int, status: Status) -> None: ...
set_status(7, "paid") # ok
set_status(7, "piad") # type checker error: not one of the allowed literals
Quantity = Annotated[int, "must be between 1 and 99"] # (2)- Optional keys inside a
TypedDict. Python 3.15 also allows typed extra keys, PEP 728. Annotatedadds metadata that tools can read; FastAPI and Pydantic use it for validation rules (FastAPI parameters).
61. How does structural pattern matching (match) work?
The short answer
match value: with case patterns, since Python 3.10, compares a value against shapes, not just equal values: literals, sequences, mappings with specific keys, class instances with specific attributes, alternatives with |, and guards with if. Patterns can capture parts into names in the same step. It shines for handling events, parsed commands and nested JSON. Cases are tried top to bottom, and case _: catches everything else. A bare name in a pattern captures rather than compares, a common trap.
python
def describe(event):
match event:
case {"type": "order.placed", "total": int(total)} if total > 10_000: # (1)
return f"big order {total}"
case {"type": "order.placed", "total": total}:
return f"order {total}"
case {"type": "refund", "items": [first, *rest]}: # (2)
return f"refund {first} +{len(rest)}"
case ["ping"] | ("ping",): # (3)
return "pong"
case _:
return "unknown"
print(describe({"type": "order.placed", "total": 25000})) # big order 25000
print(describe({"type": "order.placed", "total": 900})) # order 900
print(describe({"type": "refund", "items": ["A1", "B2", "C3"]})) # refund A1 +2
print(describe(["ping"])) # pong
print(describe(42)) # unknown- A mapping pattern with a type check, a capture and a guard.
- A sequence pattern capturing the first item and the rest.
- Alternatives with
|.
The capture trap: case PAID: with a module constant PAID = "paid" does not compare to it; it captures anything into a new name PAID. Use dotted names, such as case Status.PAID:, or literals.
62. What is the walrus operator?
The short answer
:=, the assignment expression added in Python 3.8, assigns a value and returns it in the same expression, so you can test and keep a result in one step. It is useful in while loops that read until empty, in if statements around a regex match, and in comprehensions to avoid computing something twice. Use it where it removes repetition; avoid it where a plain assignment line is clearer.
python
import re
if (m := re.match(r"ord_(\d+)", "ord_8812")): # (1)
print(m.group(1)) # 8812
while (chunk := file.read(65536)): # (2)
hasher.update(chunk)
valid = [p for raw in rows if (p := parse(raw)) is not None] # (3)- Match and test in one line, keeping the match object.
- Read until the file is exhausted, without duplicating the read call.
- Parse once, filter on the result, and keep it.
63. What changed in recent Python versions, from 3.11 to 3.15?
The short answer
3.11: about 25% faster on average, much better error locations, exception groups and except*, asyncio.TaskGroup, tomllib, and typing.Self. 3.12: the new generics syntax and type aliases, more flexible f-strings, and per-interpreter GIL internals. 3.13: a new interactive shell, experimental free-threading and JIT. 3.14: free-threading officially supported, deferred evaluation of annotations, t-strings, concurrent.interpreters, compression.zstd, and except without brackets for several types. 3.15, released October 2026: explicit lazy imports, built-in frozendict and sentinel, UTF-8 by default, unpacking in comprehensions, a faster JIT, and the Tachyon sampling profiler.
| Version | Headline features |
|---|---|
| 3.11 (2022) | Faster CPython; exception groups; TaskGroup; tomllib; precise error locations |
| 3.12 (2023) | def f[T]() generics; type aliases; f-string grammar freed up; itertools.batched |
| 3.13 (2024) | New REPL; experimental free-threaded build and JIT; better error messages |
| 3.14 (2025) | Free-threading supported; deferred annotations; t-strings; subinterpreters in Python; zstd |
| 3.15 (2026) | lazy import; frozendict; sentinel; UTF-8 default; comprehension unpacking; Tachyon profiler |
Deferred annotations in 3.14, shown:
python
def ship(order: Order) -> Receipt: ... # no NameError even if Order is defined later in the file
import annotationlib
annotationlib.get_annotations(ship, format=annotationlib.Format.STRING)
# {'order': 'Order', 'return': 'Receipt'}Annotations are no longer evaluated when the function is defined, only when something asks for them, which removes most needs for from __future__ import annotations and quoted forward references.
Which version to use: new projects should target a supported recent release, today 3.14 or 3.15. Each release gets about two years of bug fixes and five years of security fixes.
64. How does Python compare with JavaScript and TypeScript?
The short answer
Both are dynamic, garbage-collected languages with first-class functions, closures and an async/await event-loop model. The big differences: Python is strongly typed and does no implicit conversions; it uses indentation for blocks; its integers have unlimited precision; concurrency in standard CPython is limited by the GIL for CPU work, while Node has one JavaScript thread plus worker threads. TypeScript's types are erased at compile time, like Python's hints, but Python libraries such as Pydantic also use hints at runtime. Python dominates data science and ML; JavaScript dominates the browser.
| Python | JavaScript and TypeScript | |
|---|---|---|
| Typing | Dynamic, strong; optional hints | Dynamic, weak; TypeScript optional |
"3" + 4 | TypeError | "34" |
| Integers | Arbitrary precision | 64-bit floats; BigInt separately |
| Equality | == value, is identity | === strict, == coercing |
| Async | asyncio, explicit event loop | Built-in event loop, promises |
| CPU parallelism | Processes, or free-threading | Worker threads |
| Package manager | pip, uv, Poetry | npm, pnpm |
| Typical strengths | Data, ML, scripting, back ends | Front ends, full-stack, edge |
python
print(2 ** 100) # 1267650600228229401496703205376, exactjs
console.log(2 ** 100) // 1.2676506002282294e+30, a float