Core syntax, variables, lists, and common libraries.
Variables: int,str,float,boolx = 10; x = "hello"; x = [1,2,3]f-strings (f"...")f"{price:.2f}" # "9.99" | f"{name!r}" # reprWalrus operator :=while (chunk := f.read(8192)): process(chunk)match / case (3.10+)match cmd: case "quit": sys.exit() case ("go", d): move(d)try / except / else / finallytry: r=db.query() except DBError as e: log(e) else: process(r) finally: db.close()raise / raise fromexcept KeyError as e: raise ValueError("Missing key") from eassert statementassert result > 0, f"Expected positive, got {result}"global / nonlocaldef counter(): n=0; def inc(): nonlocal n; n+=1; return incList slicing [start:stop:step]nums[::-1] # reverse | nums[::2] # every other | nums[-3:]list.sort() vs sorted()sorted(users, key=lambda u: (-u.score, u.name))dict.get(k, default)count = d.get('x', 0); d.setdefault('key', []).append(1)dict merge: {**a, **b} | a|bconfig = defaults | overrides # 3.9+Set operationscommon = set_a & set_b; only_a = set_a - set_bcollections.Counterc = Counter("hello"); c.most_common(2) # [('l',2),('h',1)]collections.defaultdictgraph = defaultdict(list); graph['A'].append('B')heapq moduleheapq.heappush(h, (priority, task)); heapq.heappop(h)List comprehensionsquares = [x**2 for x in range(10) if x % 2 == 0]Dict / Set comprehensionword_len = {w: len(w) for w in words if len(w) > 3}Generator expressiontotal = sum(x**2 for x in range(1_000_000))yield / yield fromdef flatten(lst): yield from (x if not isinstance(x,list) else flatten(x) for x in lst)@functools.lru_cache@cache def fib(n): return n if n < 2 else fib(n-1)+fib(n-2)functools.partialdouble = partial(mul, 2); pow2 = partial(pow, exp=2)itertools.chain/product/groupbyfor k, g in groupby(sorted_data, key=lambda x: x.dept): ...operator modulefrom operator import attrgetter; sorted(objs, key=attrgetter('name'))@dataclass@dataclass(frozen=True, order=True) class Point: x: float; y: float__slots__class Vector: __slots__ = ('x', 'y'); def __init__(self,x,y): self.x=x; self.y=y__dunder__ methods__add__ __len__ __iter__ __contains__ __enter__ __exit__ __call__@property / @setter@property def age(self): return self._age @age.setter def age(self, v): assert v>=0; self._age=vAbstract Base Classesclass Shape(ABC): @abstractmethod def area(self) -> float: ...Protocol (structural typing)class Drawable(Protocol): def draw(self) -> None: ...__init_subclass__class Plugin(Base): def __init_subclass__(cls, **kw): REGISTRY[cls.name] = clsasyncio.gather()results = await asyncio.gather(task1(), task2(), return_exceptions=True)asyncio.create_task()task = asyncio.create_task(fetch(url)); do_other_work(); await taskasyncio.timeout() (3.11+)async with asyncio.timeout(5.0): await slow_operation()ThreadPoolExecutorresult = await loop.run_in_executor(None, blocking_db_call, args)multiprocessing.Poolwith Pool(os.cpu_count()) as p: results = p.map(process, data_chunks)concurrent.futureswith ProcessPoolExecutor() as ex: futs = [ex.submit(fn, x) for x in data]pathlib.Pathp = Path("data") / "file.csv"; text = p.read_text(encoding='utf-8')contextlib.contextmanager@contextmanager def timer(): t=time.time(); yield; print(time.time()-t)dataclasses.field()tags: list = field(default_factory=list, repr=False)typing.TypeVar / GenericT = TypeVar('T'); def first(lst: list[T]) -> T: return lst[0]typing.overload@overload def process(x: int) -> int: ... @overload def process(x: str) -> str: ...__all__ in modules__all__ = ['PublicClass', 'public_func'] # _private not exportedimportlib / __import__mod = importlib.import_module(f'plugins.{name}')