# Python essentials

Source: https://codewiki.com/cheatsheets/python/

## Bindings and branches

- `name = value` — bind or rebind a name without copying the object
- `first, *middle, last = values` — unpack the middle items into a new list
- `result = value if condition else fallback` — evaluate and return only the selected branch
- `if (match := pattern.search(text)):` — evaluate once, then retain the match object
- `match command:` — evaluate one subject against cases from top to bottom
- `case {'action': action, **rest}:` — capture one mapping value and the unmatched keys

## Collections

- `items[start:stop:step]` — select a sequence slice without changing the source
- `[project(item) for item in items if keep(item)]` — filter and transform into a new list
- `{key(item): value(item) for item in items}` — build a dictionary from generated key-value pairs
- `unique = set(items)` — deduplicate hashable values without preserving input order
- `mapping.get(key, fallback)` — return the fallback only when the key is absent
- `sorted(items, key=key_fn, reverse=True)` — return a new list ordered by a derived key

## Functions and scope

- `def fetch(url, /, timeout=5, *, retries=2):` — make `url` positional-only and `retries` keyword-only
- `def collect(*items, **options):` — collect extra positional and keyword arguments
- `result = function(*args, **kwargs)` — unpack an iterable and mapping into a call
- `nonlocal count` — rebind the nearest enclosing function binding
- `@functools.wraps(function)` — copy wrapper metadata and expose the wrapped function
- `@functools.cache` — memoize calls with an unbounded cache of hashable arguments

## Objects and ABCs

- `from abc import ABC, abstractmethod` — import the helpers for abstract base classes
- `class Service(ABC):` — declare a class governed by `ABCMeta`
- `@abstractmethod` — require concrete subclasses to override the marked method
- `super().__init__()` — call the next initializer in the method resolution order
- `@dataclass(slots=True, frozen=True)` — generate a slotted data class that blocks field assignment
- `items: list[str] = field(default_factory=list)` — create a fresh list for each data-class instance

## Iteration and lazy pipelines

- `enumerate(items, start=1)` — pair each item with a one-based counter
- `zip(left, right, strict=True)` — raise `ValueError` when iterable lengths differ
- `(project(item) for item in items)` — create a lazy generator expression
- `yield from source` — delegate iteration and generator protocol operations
- `itertools.islice(source, start, stop)` — take a lazy slice from an iterator
- `itertools.chain.from_iterable(groups)` — flatten one iterable level lazily

## Errors and cleanup

- `raise ValueError(message)` — reject an invalid value explicitly
- `raise DomainError(message) from error` — preserve the original failure as the direct cause
- `except (ValueError, TypeError) as error:` — catch only the listed exception types
- `with open(path, encoding='utf-8') as stream:` — close the text stream when the block exits
- `with contextlib.suppress(FileNotFoundError):` — ignore only the named exception from the block
- `with contextlib.ExitStack() as stack:` — release a dynamic set of resources in reverse order

## Async and concurrency

- `asyncio.run(main())` — run one top-level coroutine and close its event loop
- `result = await coroutine()` — suspend the current task until the awaitable completes
- `async with asyncio.TaskGroup() as group:` — wait for all child tasks before leaving the scope
- `task = group.create_task(work())` — start a coroutine owned by the task group
- `async with asyncio.timeout(5):` — limit the awaits inside the block to five seconds
- `result = await asyncio.to_thread(blocking_call)` — move blocking I/O off the event-loop thread

## Paths and processes

- `path = Path('data/config.toml')` — construct a path without accessing the filesystem
- `text = path.read_text(encoding='utf-8')` — read, decode, and close a text file
- `path.write_text(text, encoding='utf-8')` — overwrite, encode, and close a text file
- `path.mkdir(parents=True, exist_ok=True)` — create missing parent directories idempotently
- `result = subprocess.run(args, check=True, text=True, capture_output=True)` — capture text output and raise on a nonzero exit status
- `with tempfile.TemporaryDirectory() as directory:` — remove the temporary directory when the block exits

## Data boundaries

- `data = json.loads(text)` — parse JSON text into Python values
- `text = json.dumps(data, ensure_ascii=False)` — serialize JSON without escaping non-ASCII characters
- `with path.open(newline='', encoding='utf-8') as stream:` — let the CSV module handle embedded newlines correctly
- `rows = csv.DictReader(stream)` — read each CSV record as a header-keyed mapping
- `digest = hashlib.sha256(payload).hexdigest()` — hash bytes and return the digest as hexadecimal text
- `token = secrets.token_urlsafe(32)` — generate a URL-safe token from 32 random bytes

## Text and time

- `clean = ' '.join(text.split())` — trim and collapse runs of whitespace
- `match = re.fullmatch(r'[A-Z]{2}\d{4}', text)` — require the regular expression to match the whole string
- `block = textwrap.dedent(block)` — remove indentation shared by nonblank lines
- `now = datetime.now(timezone.utc)` — create an aware current UTC datetime
- `stamp = datetime.fromisoformat(text)` — parse a supported ISO 8601 date-time string
- `local = now.astimezone(ZoneInfo('Europe/Paris'))` — convert the same instant to an IANA time zone

## Type hints

- `name: str = value` — annotate a binding for static tools without runtime enforcement
- `def parse(text: str) -> int:` — annotate parameter and return types
- `type Result[T] = T | Exception` — declare a generic type alias
- `def first[T](items: Sequence[T]) -> T:` — declare a generic function with one type parameter
- `class Reader(Protocol):` — describe a structural interface for static checking
- `class Config(TypedDict):` — describe the expected keys and values of a dictionary

## Testing and local tools

- `python -m venv .venv` — create an isolated virtual environment
- `python -m unittest -v` — discover and run standard-library tests verbosely
- `python -m pdb script.py` — start the script under the Python debugger
- `breakpoint()` — pause at the configured debugger hook
- `python -m compileall src` — precompile source files to bytecode
- `python -m timeit 'sum(range(1000))'` — benchmark a small statement repeatedly
