from __future__ import annotations import asyncio from contextlib import contextmanager from dataclasses import dataclass @dataclass class Point: x: int y: int @contextmanager def tagged(name: str): yield f'<{name}>' def describe(value): match value: case Point(0, y): return f'y-axis:{y}' case Point(x=x, y=y) if x == y: return f'diagonal:{x}' case {'kind': 'pair', 'items': [first, *rest], **extra}: return f'pair:{first}:{len(rest)}:{sorted(extra)}' case ('wrap', inner as captured): return f'wrapped:{inner}:{captured}' case [head, *tail]: return f'list:{head}:{sum(tail)}' case _: return 'unknown' async def async_total(values): total = 0 for value in values: await asyncio.sleep(0) total += value return total def make_counter(start=0): count = start def next_value(step=1): nonlocal count count += step return count return next_value class Box: def __init__(self, value): self.value = value @property def doubled(self): return self.value * 2 def run() -> None: items = [ Point(0, 7), Point(4, 4), {'kind': 'pair', 'items': [3, 5, 8], 'tag': 'fib'}, ('wrap', 'token'), [1, 2, 3, 4], object(), ] print('descriptions:', [describe(item) for item in items]) print('async:', asyncio.run(async_total([1, 2, 3, 4]))) counter = make_counter(10) print('counter:', [counter(), counter(5), counter()]) with tagged('ctx') as label: print('context:', label) print('box:', Box(9).doubled) print('bytes:', bytes([65, 66, 67]).decode()) print('format:', f'{255:#06x}:{3.14159:.2f}') if __name__ == '__main__': run()