The syntax, standard library, and gotchas that show up in every Python screening round.
Data Types & Basics
Primitive types and isinstance
int, float, complex, bool, str, bytes, NoneType. bool is a subclass of int (True == 1). isinstance() respects inheritance and accepts a tuple of types; type() checks the exact class.
type(42) # <class 'int'>
isinstance(True, int) # True (bool subclasses int)
type(True) is int # False
isinstance(x, (int, float, str))
Mutable vs immutable
Immutable: int, float, str, tuple, frozenset, bytes. Mutable: list, dict, set, bytearray. Mutables cannot be dict keys or set elements. Immutables are hashable only if their contents are too — a tuple holding a list is unhashable.
s = 'hi'; s += '!' # new string object
lst = [1]; lst.append(2) # same object mutated
{[1]: 2} # TypeError: unhashable type: 'list'
hash((1, [2])) # TypeError: tuple contains a list
Truthiness
Falsy: None, False, 0, 0.0, 0j, '', [], {}, set(), frozenset(). Everything else truthy, including '0', [0], and non-empty containers.
bool(0) # False
bool('0') # True
bool([]) # False
if lst: # idiomatic non-empty check
process(lst)
None vs False vs 0
None is the singleton null. None == False is False; use is None (identity, not overridable __eq__). 0 == False is True because bool subclasses int.
x is None # correct
x == None # works but discouraged
None == False # False
0 == False # True
Integer arbitrary precision
Python ints have unlimited precision (memory-limited). No overflow. // is floor division, % modulo, ** exponent. divmod returns (q, r).
2 ** 1000 # huge int
10 // 3 # 3
-10 // 3 # -4 (floor)
divmod(10, 3) # (3, 1)
Float precision
Floats are IEEE-754 doubles, so 0.1 + 0.2 != 0.3. Use math.isclose for comparisons and decimal.Decimal for exact decimal arithmetic (money).
import math
0.1 + 0.2 == 0.3 # False
0.1 + 0.2 # 0.30000000000000004
math.isclose(0.1 + 0.2, 0.3) # True
from decimal import Decimal
Decimal('0.1') + Decimal('0.2') == Decimal('0.3') # True
String immutability and interning
Strings are immutable; operations create new objects. Short literals are interned, so a is b may be True — an implementation detail. Compare with ==, and use is only for singletons (None, True, False).
a = 'hello'; b = 'hello'
a == b # True (correct)
a is b # maybe True (interned), don't rely
Type conversion
int(), float(), str(), bool(), list(), tuple(), set(), dict(). int('10', 2) parses a base. Conversion raises ValueError on bad input. bool() of a non-empty container is True.
int('10', 2) # 2
int(3.9) # 3 (truncates)
float('inf') # inf
list('abc') # ['a','b','c']
Object identity, __eq__ and __hash__
__eq__ defines ==; __hash__ defines hash(). Default is identity-based. Defining __eq__ sets __hash__ = None (unhashable) unless you define it too. Equal objects must have equal hashes.
a = [1, 2]; b = [1, 2]
a == b # True (list __eq__)
a is b # False
class P:
def __init__(self, x): self.x = x
def __eq__(self, o): return self.x == o.x
# __hash__ is None -> unhashable
Copying: shallow vs deep
Assignment binds a new name to the same object. copy.copy and list[:] copy one level (nested objects shared); copy.deepcopy is recursive. Use deepcopy when nested mutables must be independent.
import copy
a = [1, [2]]
b = a # same object
c = a[:] # shallow: c[1] is a[1]
d = copy.deepcopy(a) # fully independent
c[1].append(3) # also mutates a
Small integer caching
CPython caches ints in [-5, 256], so is is True there. Outside that range the result may be either: literals in the same compilation unit are folded to one object (a = 257; b = 257; a is b is often True in a script or on one REPL line), while separately computed values are usually distinct. Always compare with ==.
a = 256; b = 256; a is b # True (cached)
a = 257; b = 257; a is b # may be True (constant folding) or False
a = int('257'); b = int('257'); a is b # False
Strings
f-strings
Formatted string literals (3.6+). Expressions in {}, format spec after a colon. Fastest and most readable. Supports = for debugging (3.8+).
name = 'Ada'; age = 36
f'{name} is {age}'
f'{name=}, {age=}' # debug: name='Ada', age=36
f'{value:.2f}'
str.format and % formatting
str.format takes positional or named placeholders. % formatting is legacy C-style. Prefer f-strings; format is still useful for templates stored as data.
'Hello, {}!'.format(name)
'{x} + {y}'.format(x=1, y=2)
'Value: %d' % 42
String slicing
s[start:stop:step]. Negative indices count from the end. Omit bounds freely. Step -1 reverses. Slicing never raises IndexError (it clamps).
s = 'python'
s[1:4] # 'yth'
s[::-1] # 'nohtyp'
s[-2:] # 'on'
s[10:20] # '' (no error)
Common string methods
strip/split/join/replace/find/count/startswith/endswith. Methods return new strings (immutable). split with no argument splits on runs of whitespace and strips.
' a b '.split() # ['a','b']
','.join(['a','b']) # 'a,b'
s.replace('old','new')
s.startswith('py')
s.strip()
join vs concatenation
str.join(iterable) is O(n) total; repeated += in a loop is O(n²) because each step creates a new string. Use join or io.StringIO for many pieces.
''.join(parts) # efficient
# avoid: result = ''
# for p in parts: result += p
Regex basics (re)
re.search/findall/sub/match/fullmatch. Use raw strings r''. Compile for reuse. Groups via parentheses; named groups via (?P<name>).
import re
re.findall(r'\d+', 'a1b23') # ['1','23']
re.sub(r'\s+', ' ', text)
m = re.search(r'(?P<year>\d{4})', s)
m.group('year')
Bytes vs str
str is Unicode text; bytes is raw data. Encode/decode between them. File I/O defaults to text (str); use 'rb'/'wb' for bytes. Mixing raises TypeError.
'café'.encode('utf-8') # b'caf\xc3\xa9'
b'caf\xc3\xa9'.decode('utf-8') # 'café'
len('café'), len('café'.encode()) # 4 5
Multiline strings
Triple-quoted strings preserve newlines and indentation. Use textwrap.dedent to clean them up. Docstrings are triple-quoted first statements.
msg = '''Line 1
Line 2'''
import textwrap
textwrap.dedent(msg)
String formatting specifiers
Format mini-language: width, precision, alignment, fill, type. f'{x:>10.2f}' right-aligns at width 10 with 2 decimals. Useful for tables.
f'{42:>8}' # ' 42'
f'{3.14159:.2f}' # '3.14'
f'{1000:,}' # '1,000'
in operator for substrings
'sub' in 'string' checks a substring in O(n). Membership in a list is O(n); in a set or dict keys it is O(1).
'py' in 'python' # True
'x' in ['a','b'] # False
'x' in {'x': 1} # True (keys)
str.splitlines and partition
splitlines handles universal newlines (\n, \r\n, \r) and drops them. partition splits into a 3-tuple at the first occurrence and never raises.
'a\nb\r\nc'.splitlines() # ['a','b','c']
'key=value'.partition('=') # ('key', '=', 'value')
'missing'.partition('=') # ('missing', '', '')
Lists & Tuples
List methods
append, extend, insert, pop, remove, index, count, sort, reverse, clear, copy. append adds one element; extend adds elements of an iterable. sort mutates (use sorted for a new list).
lst = [1,2,3]
lst.append(4) # [1,2,3,4]
lst.extend([5,6]) # [1,2,3,4,5,6]
lst.pop() # 6
lst.remove(2) # removes first 2
List slicing and assignment
Slice assignment can change length: lst[1:3] = [9,9,9]. Delete a slice with del lst[1:3]. Slicing creates a shallow copy.
lst = [1,2,3,4]
lst[1:3] = [9,9,9] # [1,9,9,9,4]
del lst[1:3] # [1,9,4]
copy = lst[:]
List comprehensions
Concise transform/filter: [expr for x in iterable if cond]. Nested loops read left-to-right. Also dict/set comprehensions and generator expressions.
[x*x for x in range(10) if x % 2 == 0]
{x: x*x for x in range(5)}
(x*x for x in range(10)) # generator (lazy)
Tuple unpacking
Unpack an iterable into names: a, b = (1, 2). A star captures the rest: first, *rest = lst. Swap without a temp: a, b = b, a. Works in for loops.
a, b = (1, 2)
first, *rest = [1,2,3,4] # rest=[2,3,4]
a, b = b, a # swap
for k, v in d.items(): pass
Tuple immutability nuance
A tuple itself is immutable (items cannot be reassigned), but its elements can be mutable. It is hashable only if all elements are. A one-element tuple needs a trailing comma.
t = (1, [2,3])
t[1].append(4) # allowed (mutable element)
t[0] = 5 # TypeError
single = (1,) # tuple
not_tuple = (1) # int
List as stack and queue
list append/pop is an O(1) stack (LIFO). For a FIFO queue use collections.deque (append/popleft are O(1)); list.pop(0) is O(n).
stack = []; stack.append(1); stack.pop()
from collections import deque
q = deque(); q.append(1); q.popleft()
sorted vs sort
sorted() returns a new list (works on any iterable). list.sort() mutates in place and returns None. Both accept key and reverse.
sorted([3,1,2]) # [1,2,3]
lst.sort(reverse=True) # mutates
sorted(words, key=len) # by length
enumerate and zip
enumerate adds an index: for i, x in enumerate(lst). zip pairs elements and stops at the shortest; zip_longest fills. Unzip with zip(*pairs).
list(enumerate(['a','b'])) # [(0,'a'),(1,'b')]
list(zip([1,2],[3,4])) # [(1,3),(2,4)]
a, b = zip(*pairs) # unzip
List multiplication and aliasing
lst * n repeats references (shallow). [[0]*3]*3 creates shared inner lists — a classic bug. Use a comprehension to make independent rows.
[[0]*3 for _ in range(3)] # independent rows
# bug: [[0]*3]*3 (shared rows)
any and all
any() is True if any element is truthy (short-circuits). all() is True if every element is truthy. Empty: any([]) is False, all([]) is True (vacuous).
any(x > 0 for x in lst)
all(isinstance(x, int) for x in lst)
all([]) # True
Dictionaries & Sets
Dict basics and ordering
Hash map, insertion-ordered since 3.7 (guaranteed). O(1) average get/set. Keys must be hashable. Use .get(key, default) to avoid KeyError.
d = {'a': 1}
d.get('b', 0) # 0
d['c'] = 3
'a' in d # True (keys)
Dict methods
keys/values/items return live views. pop, popitem (LIFO), update (merge), setdefault, fromkeys. Views reflect later dict changes.
d.keys(); d.values(); d.items()
d.pop('a')
d.update({'x': 1})
d.setdefault('k', []).append(1)
Dict comprehensions
{k: v for ... if ...}. Transform or filter dicts. Merge with {**a, **b} or the | operator (3.9+).
{k: v*2 for k, v in d.items() if v > 0}
merged = a | b # 3.9+ (b wins)
{**a, **b}
defaultdict
collections.defaultdict(factory) creates a default on missing-key access. Great for grouping and counting. The factory is called with no arguments.
from collections import defaultdict
g = defaultdict(list)
g['a'].append(1) # no KeyError
counts = defaultdict(int)
counts['x'] += 1 # starts at 0
Counter
collections.Counter counts hashable items. most_common, arithmetic, subtract. counter['missing'] returns 0 without raising.
from collections import Counter
c = Counter('abracadabra')
c.most_common(2) # [('a',5),('b',2)]
c['z'] # 0
Set operations
A set holds unique hashable elements with O(1) membership. Union |, intersection &, difference -, symmetric difference ^. Methods with the same names are also available.
a = {1,2,3}; b = {2,3,4}
a | b # {1,2,3,4}
a & b # {2,3}
a - b # {1}
a ^ b # {1,4}
frozenset
Immutable, hashable set. Usable as a dict key or set element — useful for sets of sets or memoizing on a set.
fs = frozenset({1,2,3})
{fs: 'value'} # valid dict key
frozenset({1,2}) in {frozenset({1,2})}
Set membership and performance
x in set is O(1) average vs O(n) for a list. Convert a list to a set for repeated membership tests. Sets are unordered and not indexable.
s = set(lst)
if x in s: ... # O(1)
Dict view objects
keys()/values()/items() return dynamic views, not lists. Keys and items support set-like operations. Convert with list() when you need a snapshot.
d.keys() & other.keys() # intersection of key sets
list(d.items())
Walrus and dict get patterns
Use setdefault or defaultdict to accumulate lists. Walrus := can simplify read loops.
# grouping
groups = {}
for x in items:
groups.setdefault(x.type, []).append(x)
# walrus
while (line := f.readline()): process(line)
OrderedDict vs dict
Since 3.7 a regular dict preserves insertion order. OrderedDict is still useful for move_to_end and order-sensitive equality. Most code should use dict.
from collections import OrderedDict
od = OrderedDict()
od.move_to_end('key')
Functions
*args and **kwargs
*args collects extra positional args into a tuple; **kwargs collects extra keyword args into a dict. Use them for flexible signatures and forwarding. Order: positional, *args, keyword-only, **kwargs.
def f(a, *args, b=2, **kwargs):
print(a, args, b, kwargs)
f(1, 3, 4, x=5) # 1 (3,4) 2 {'x':5}
Mutable default argument trap
Default args are evaluated once at function definition. Mutable defaults (list/dict) are shared across calls. Use a None sentinel.
def f(x, acc=[]): # BUG: shared list
acc.append(x); return acc
def f(x, acc=None): # correct
if acc is None: acc = []
acc.append(x); return acc
Late binding in closures
Closures capture variables by reference, not value, so loop closures see the final value. Fix by binding the current value as a default argument.
funcs = []
for i in range(3):
funcs.append(lambda: i) # all return 2
# fix:
funcs = [lambda i=i: i for i in range(3)]
Decorators
@decorator wraps a function. Common ones: @property, @classmethod, @staticmethod, @lru_cache, @dataclass. Implement with functools.wraps to preserve metadata.
from functools import wraps
def log(fn):
@wraps(fn)
def wrapper(*a, **k):
print(f'calling {fn.__name__}')
return fn(*a, **k)
return wrapper
@log
def add(a, b): return a + b
Generators and yield
A function with yield returns a generator (a lazy iterator). Memory-efficient for large or infinite sequences. send() feeds values in; yield from delegates.
def gen(n):
for i in range(n):
yield i
g = gen(5)
next(g) # 0
list(gen(3)) # [0,1,2]
Generator expressions
Lazy version of a list comprehension in parentheses. Streams values instead of building a list. Can be passed to a function without extra parens.
sum(x*x for x in range(10**6)) # memory-efficient
(x for x in lst if x > 0)
lambda
Anonymous single-expression function: lambda x: x*x. Use for short callbacks; prefer def for anything complex. Cannot contain statements.
sorted(items, key=lambda x: x.name)
list(map(lambda x: x*2, nums))
Closures capturing variables
An inner function can read outer variables and rebind them with nonlocal. Closures enable factory functions and private state.
def make_counter(start=0):
n = start
def inc():
nonlocal n
n += 1
return n
return inc
functools.partial
Fixes some arguments of a function, returning a new callable. Useful for configuring callbacks and adapters.
from functools import partial
def power(base, exp): return base ** exp
square = partial(power, exp=2)
square(5) # 25
lru_cache memoization
functools.lru_cache caches results by argument. Great for pure functions and naive recursion. maxsize bounds the cache; arguments must be hashable. functools.cache is the unbounded alias (3.9+).
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
Keyword-only and positional-only params
Params after * (or *args) are keyword-only. Params before / (3.8+) are positional-only. This enforces the calling convention you want to support.
def f(a, /, b, *, c):
# a positional-only, c keyword-only
return a + b + c
f(1, 2, c=3)
First-class functions
Functions are objects: assign them, pass them, return them. This enables higher-order functions and the map/filter/reduce style.
def apply(f, x): return f(x)
def double(x): return x*2
apply(double, 5) # 10
Type Hints & Typing
Type hints basics
Annotations are optional and not enforced at runtime. Use builtin generics (list[int], dict[str, int], 3.9+) and X | None (3.10+) instead of Optional/Union. Python 3.14 evaluates annotations lazily by default (PEP 649), so forward references need no quotes.
def greet(name: str, times: int = 1) -> str:
return f'hi {name}' * times
def find(ids: list[int], key: str | None = None) -> dict[str, int]: ...
Protocol (structural typing)
typing.Protocol describes an interface by shape: any class with matching members satisfies it, with no inheritance. runtime_checkable enables isinstance (checks member presence only). Prefer it over an ABC for duck-typed boundaries.
from typing import Protocol
class Closeable(Protocol):
def close(self) -> None: ...
def shutdown(x: Closeable) -> None:
x.close()
# class Socket: def close(self): ... # satisfies it
TypedDict
TypedDict types a dict with a fixed set of string keys. Required/NotRequired (3.11+) mark optional keys. At runtime it is still a plain dict; use pydantic or dataclasses if you need validation.
from typing import TypedDict, NotRequired
class Movie(TypedDict):
title: str
year: NotRequired[int]
m: Movie = {'title': 'Alien'}
Generics and PEP 695
PEP 695 (3.12+) adds class Stack[T], def first[T](...), and type Alias = ..., replacing TypeVar boilerplate. Bounds use T: int; constraints use T: (int, str). Before 3.12: TypeVar and Generic[T].
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, x: T) -> None:
self._items.append(x)
def first[T](xs: list[T]) -> T:
return xs[0]
type Pair[T] = tuple[T, T]
Callable, Literal, Final, overload
Callable[[int], str] types a function. Literal restricts a value to constants, Final marks constants, @overload declares multiple signatures for one implementation. Prefer object over Any when you mean any object safely.
from typing import Callable, Literal, Final
Handler = Callable[[int], str]
mode: Literal['r', 'w'] = 'r'
MAX: Final = 100
Static checking and runtime introspection
Python ignores hints; mypy or pyright enforces them statically. Use isinstance for runtime narrowing, get_type_hints() to read annotations, and dataclasses/pydantic for runtime validation.
from typing import get_type_hints
get_type_hints(greet)
# {'name': str, 'times': int, 'return': str}
OOP
Class basics
__init__ initializes an instance; self is the explicit instance reference. Class attributes are shared; instance attributes are per-object. __attr is name-mangled for a soft private.
class Dog:
species = 'Canis'
def __init__(self, name):
self.name = name
def bark(self):
return f'{self.name} woofs'
classmethod vs staticmethod
@classmethod receives cls and is used for alternative constructors. @staticmethod has no implicit first argument and just namespaces a utility in the class. @property exposes a computed attribute.
class User:
@classmethod
def from_dict(cls, d): return cls(d['name'])
@staticmethod
def validate(email): return '@' in email
@property
Turns a method into attribute access with getter/setter/deleter. Enables validation, computed values, and backward-compatible attribute changes.
class Circle:
def __init__(self, r): self._r = r
@property
def area(self): return 3.14159 * self._r ** 2
@area.setter
def area(self, v): self._r = (v/3.14159)**0.5
Inheritance and super()
class Child(Parent). super() returns an MRO-aware proxy to the parent. Use it to extend behavior rather than replace it. Multiple inheritance is supported but adds complexity.
class Animal:
def speak(self): return '...'
class Dog(Animal):
def speak(self):
return 'Woof! ' + super().speak()
MRO (Method Resolution Order)
C3 linearization determines lookup order for multiple inheritance. Inspect it with Class.__mro__ or mro(). The diamond problem resolves predictably.
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
D.__mro__ # D, B, C, A, object
Dunder methods
__str__ (user-friendly), __repr__ (developer/debug, ideally eval-able), __len__, __eq__, __hash__, __iter__, __getitem__, __call__, __enter__/__exit__ (context manager).
class Point:
def __init__(self, x, y): self.x, self.y = x, y
def __repr__(self): return f'Point({self.x},{self.y})'
def __eq__(self, o): return (self.x,self.y) == (o.x,o.y)
dataclass
@dataclass generates __init__, __repr__, and __eq__. Use frozen=True for immutability, field(default_factory=...) for mutable defaults, and order=True for comparisons.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Point:
x: int
y: int = 0
tags: list = field(default_factory=list)
__slots__
Declares a fixed attribute set; avoids __dict__, reducing memory and speeding attribute access. You cannot add arbitrary attributes. Inherit carefully.
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x, self.y = x, y
# p.z = 1 # AttributeError
Abstract base classes
abc.ABC with @abstractmethod enforces implementation in subclasses. An abstract class cannot be instantiated. Use it for explicit interfaces and contracts.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
class Circle(Shape):
def area(self): return 3.14 * self.r**2
Composition over inheritance
Prefer has-a over is-a. Inject dependencies: easier to test and change. Use inheritance for true specialization and composition for behavior assembly.
class Car:
def __init__(self, engine):
self.engine = engine
def start(self):
return self.engine.start()
Descriptors
Objects implementing __get__/__set__/__delete__ control attribute access. They underlie property, classmethod, and slots. Use them for reusable validation.
class Validated:
def __set_name__(self, owner, name): self.name = name
def __get__(self, obj, objtype=None): return obj.__dict__.get(self.name)
def __set__(self, obj, value):
if value < 0: raise ValueError
obj.__dict__[self.name] = value
__new__ vs __init__
__new__ creates and returns the instance (first argument cls); __init__ initializes it and must return None. Override __new__ for immutables, caches, or singletons. If __new__ returns an existing object, __init__ still runs on it.
class Singleton:
_inst = None
def __new__(cls):
if cls._inst is None:
cls._inst = super().__new__(cls)
return cls._inst
def __init__(self):
pass # runs on every call
Metaclasses and __init_subclass__
type is the default metaclass; class C(metaclass=M) lets M create and modify classes (registration, validation, singletons). Prefer __init_subclass__ (3.6+) for subclass hooks and __set_name__ for descriptors — both avoid metaclass conflicts.
class Registry:
subs = []
def __init_subclass__(cls, **kw):
super().__init_subclass__(**kw)
Registry.subs.append(cls)
class A(Registry): pass
Registry.subs # [A]
Enum
enum.Enum gives named constants; members are singletons with .name and .value. IntEnum/StrEnum compare equal to their values, Flag handles bitmasks, @unique rejects duplicate values. auto() assigns values.
from enum import Enum, auto, StrEnum
class Color(Enum):
RED = auto()
GREEN = auto()
Color.RED.name, Color.RED.value # ('RED', 1)
class Role(StrEnum):
ADMIN = 'admin'
Role.ADMIN == 'admin' # True
Iterators & Generators
Iterable vs iterator
An iterable implements __iter__ returning an iterator. An iterator implements __iter__ and __next__. for calls iter() then next() until StopIteration. Lists are iterable, not iterators.
it = iter([1,2,3])
next(it) # 1
next(it) # 2
# next([1,2]) # TypeError: list is not an iterator
Custom iterator class
Implement __iter__ (return self) and __next__ (raise StopIteration when done) to support for loops over custom objects.
class Counter:
def __init__(self, n): self.n = n; self.i = 0
def __iter__(self): return self
def __next__(self):
if self.i >= self.n: raise StopIteration
self.i += 1; return self.i
yield from delegation
yield from delegates iteration to a subgenerator and returns its return value. It simplifies flattening and forwarding, and propagates send/throw/close.
def flatten(nested):
for sub in nested:
yield from sub
list(flatten([[1,2],[3]])) # [1,2,3]
itertools essentials
chain (concatenate), islice (lazy slicing), product (cartesian), permutations, combinations, groupby (consecutive groups), accumulate, tee, count, cycle, repeat.
from itertools import chain, islice, product, groupby
list(chain([1,2],[3,4])) # [1,2,3,4]
list(islice(range(100), 5)) # [0,1,2,3,4]
list(product('ab', '12')) # [('a','1'),('a','2'),...]
Generator pipelines
Chain generators for memory-efficient processing. Each stage pulls lazily, which is ideal for large files and streams.
def read_lines(f): ...
def parse(lines): ...
def filter_valid(records): ...
for r in filter_valid(parse(read_lines(f))): process(r)
send() and coroutines
generator.send(value) resumes with value as the result of the yield expression. This enables two-way communication. Prime with next() or send(None) first.
def averager():
total = 0; count = 0
while True:
value = yield (total/count if count else 0)
total += value; count += 1
avg = averager(); next(avg)
avg.send(10); avg.send(20)
StopIteration in generators
Raising StopIteration inside a generator becomes RuntimeError (PEP 479) to prevent silent truncation. Use return to end a generator.
def g():
yield 1
return # ends generator cleanly
# raise StopIteration # RuntimeError in 3.7+
tee for splitting iterators
itertools.tee splits one iterator into n independent iterators. It buffers consumed values in memory, so use it only when the same source must be walked twice.
from itertools import tee
a, b = tee(gen())
list(a); list(b) # both full
iter with sentinel
iter(callable, sentinel) calls callable until it returns sentinel. Useful for reading fixed-size chunks or C-style loops.
with open('f') as f:
for chunk in iter(lambda: f.read(1024), ''):
process(chunk)
Memory efficiency
Generators process one item at a time; lists materialize everything. Trade-off: a generator can only be iterated once.
# memory-heavy
data = [transform(x) for x in huge]
# memory-light
data = (transform(x) for x in huge)
Exceptions & Error Handling
try/except/else/finally
except matches the first compatible class; else runs when no exception occurred; finally always runs, even on return. Chain with raise NewError(...) from e and inspect __cause__; bare raise re-raises the active exception.
try:
v = int(s)
except ValueError as e:
raise ConfigError('bad int') from e
else:
use(v)
finally:
cleanup()
Custom exceptions
Subclass Exception (not BaseException). Store context as attributes. Keep a module-level hierarchy so callers can catch broadly or narrowly. Do not use exceptions for normal control flow.
class AppError(Exception): ...
class NotFound(AppError):
def __init__(self, key):
super().__init__(f'missing {key}')
self.key = key
Exception groups and except* (3.11+)
An ExceptionGroup bundles several exceptions; asyncio.TaskGroup raises one. except* handles each subgroup by type and re-raises whatever is unhandled. A plain except cannot catch a group by type.
try:
raise ExceptionGroup('boom', [ValueError('v'), TypeError('t')])
except* ValueError as eg:
print(eg.exceptions) # (ValueError('v'),)
# TypeError still propagates
contextlib.suppress and ExitStack
suppress swallows only the listed exceptions. ExitStack manages a dynamic set of context managers. A context manager's __exit__ can suppress an exception by returning True.
from contextlib import suppress, ExitStack
with suppress(FileNotFoundError):
os.remove('maybe.txt')
with ExitStack() as stack:
files = [stack.enter_context(open(p)) for p in paths]
Async & Concurrency
async/await basics
async def defines a coroutine function; calling it returns a coroutine object that does not run until awaited. await suspends until the awaitable completes. Coroutines must run inside an event loop.
import asyncio
async def fetch():
await asyncio.sleep(1)
return 42
asyncio.run(fetch())
asyncio.gather
Runs awaitables concurrently and returns results in argument order. The first exception propagates to the awaiter, and the other tasks keep running (they are not cancelled). return_exceptions=True collects results and exceptions instead. For new code prefer asyncio.TaskGroup (3.11+), which cancels siblings on failure.
results = await asyncio.gather(task1(), task2(), task3())
# collect failures instead of raising
await asyncio.gather(*tasks, return_exceptions=True)
asyncio.TaskGroup (3.11+)
The preferred structured-concurrency API. Tasks start inside async with; the block exits only when all finish. Any failure cancels the remaining tasks and raises an ExceptionGroup.
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch(a))
t2 = tg.create_task(fetch(b))
print(t1.result(), t2.result())
asyncio.create_task
Schedules a coroutine as a Task on the running loop so it runs concurrently. Use it for fire-and-forget or to start work before awaiting. Keep a reference to avoid the task being garbage-collected.
task = asyncio.create_task(work())
# ... other work ...
result = await task
Event loop
A single thread runs tasks cooperatively; tasks yield at await points. Blocking calls (time.sleep, heavy CPU) stall the whole loop — use asyncio.sleep, asyncio.to_thread, or a process pool.
# blocking in async is bad:
time.sleep(1) # blocks loop
await asyncio.sleep(1) # yields
Threading
threading is for I/O-bound concurrency. Threads share memory; the GIL serializes bytecode on standard CPython, but the free-threaded build runs CPU-bound threads in parallel. Use ThreadPoolExecutor and locks for shared mutable state.
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as ex:
results = list(ex.map(fetch, urls))
Multiprocessing
Separate processes bypass the GIL for CPU-bound work. Args and results are pickled, so overhead matters. Use ProcessPoolExecutor; share state via Queue/Pipe/Manager.
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as ex:
results = list(ex.map(cpu_heavy, data))
GIL (Global Interpreter Lock)
On standard CPython, one thread executes Python bytecode at a time; threads still help I/O because the GIL is released during I/O. The free-threaded (no-GIL) build is the answer for 2026: PEP 703 made it experimental in 3.13 and PEP 779 made it officially supported in 3.14, where CPU-bound threads run in parallel. On standard builds, use processes for CPU-bound work.
# standard build: I/O -> threads or asyncio
# CPU -> multiprocessing
# free-threaded build (3.13+): CPU-bound threads
# run with python3.14t script.py ('t' = free-threaded)
asyncio synchronization
asyncio.Lock, Semaphore, Event, Condition, and Queue coordinate coroutines. Do not use threading locks in async code — acquiring one can block the loop.
sem = asyncio.Semaphore(3)
async with sem:
await do_work()
run_in_executor and to_thread
Offload blocking sync code to a thread or process pool without blocking the loop. Inside a coroutine use asyncio.get_running_loop() (get_event_loop() is deprecated there); simplest is await asyncio.to_thread(fn, arg) (3.9+).
result = await asyncio.to_thread(blocking_fn, arg)
# explicit pool / process pool
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(None, blocking_fn, arg)
async context managers and async generators
async with uses __aenter__/__aexit__. async for uses __aiter__/__anext__. An async generator uses async def + yield. Use them for async streams and resource cleanup.
async def gen():
for i in range(3):
await asyncio.sleep(0.1)
yield i
async for x in gen(): print(x)
File I/O & Context Managers
open modes
open(path, mode): 'r' read text, 'w' write (truncate), 'a' append, 'x' exclusive create, 'b' binary, '+' read+write. Always specify encoding for text.
with open('data.txt', 'r', encoding='utf-8') as f:
text = f.read()
with statement / context manager
Guarantees cleanup (__exit__) even on exceptions. Used for files, locks, DB connections. contextlib.contextmanager builds one from a generator.
from contextlib import contextmanager
@contextmanager
def managed():
setup()
try: yield resource
finally: teardown()
Reading files
read() reads everything, readline() one line, readlines() a list, and iteration streams line by line (memory-efficient). read().splitlines() drops trailing newlines.
with open('f') as f:
for line in f: # streams
process(line.rstrip('\n'))
Writing files
write() does not add a newline and neither does writelines(). Use print(file=f) for newlines. Buffered data is flushed on flush() or close().
with open('out.txt', 'w') as f:
f.write('hello\n')
print('world', file=f)
pathlib
pathlib.Path is the modern path API: / operator, read_text/write_text, glob, exists, is_file, mkdir, resolve. Prefer it over os.path.
from pathlib import Path
p = Path('dir') / 'file.txt'
p.read_text(encoding='utf-8')
p.write_text('hi')
list(Path('.').glob('*.py'))
JSON I/O
json.load/dump work with files; loads/dumps with strings. Use ensure_ascii=False for Unicode output and default= for non-serializable objects.
import json
data = json.loads(s)
json.dump(data, f, indent=2, ensure_ascii=False)
json.dump(obj, f, default=str)
CSV I/O
The csv module handles quoting. Use DictReader/DictWriter for header-based rows. Always open with newline=''.
import csv
with open('f', newline='') as f:
reader = csv.DictReader(f)
for row in reader: print(row['name'])
Binary I/O
Open with 'rb'/'wb' and read/write bytes. Use struct for binary formats and pickle only for trusted Python objects (unpickling untrusted data can execute code).
with open('img.png', 'rb') as f:
data = f.read()
import pickle
pickle.dump(obj, f) # only trusted data
Temporary files
tempfile.NamedTemporaryFile and TemporaryDirectory clean up automatically. Use them for intermediate processing.
import tempfile
with tempfile.TemporaryDirectory() as d:
path = Path(d) / 'tmp.txt'
path.write_text('x')
File encoding and errors
Specify encoding='utf-8'. Use errors='replace'/'ignore'/'strict' for decoding problems. Text mode handles universal newlines.
open('f', encoding='utf-8', errors='replace')
open('f', encoding='utf-8', newline='') # preserve newlines
os and shutil
os.remove, os.rename, os.makedirs(exist_ok=True). shutil.copy, copytree, rmtree, move. pathlib covers many cases; shutil handles whole trees.
import shutil, os
os.makedirs('a/b', exist_ok=True)
shutil.copy('src', 'dst')
shutil.rmtree('dir')
Packaging & Environment
Virtual environments
python -m venv .venv creates an isolated interpreter. Activate it before installing anything. Never install project dependencies globally, and use python -m pip so pip matches the interpreter.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
pyproject.toml
The standard project file: [project] holds metadata and dependencies, [build-system] selects the backend (setuptools, hatchling, uv_build), and [tool.*] configures pytest, ruff, mypy. It replaces setup.py/setup.cfg.
[project]
name = 'app'
version = '0.1.0'
requires-python = '>=3.11'
dependencies = ['httpx>=0.27']
[build-system]
requires = ['hatchling']
build-backend = 'hatchling.build'
uv project workflow
uv is a fast Rust package/project manager: uv init, uv add, uv run, uv sync, uv lock (uv.lock), plus uv python install. It creates and manages the virtualenv for you.
uv init app && cd app
uv add httpx
uv run pytest
uv sync --frozen # CI: install exactly the lockfile
Building and publishing
python -m build produces an sdist and wheel; twine upload (or uv publish) ships them. Console scripts come from [project.scripts]. Applications pin a lockfile; libraries use compatible version ranges.
[project.scripts]
app = 'app.cli:main'
python -m build
twine upload dist/*
Testing with pytest
pytest basics
pytest discovers test_*.py / *_test.py files and test_* functions. Plain assert is rewritten for detailed failure output. Use pytest.raises for exceptions and pytest.approx for floats.
import pytest
def test_add():
assert add(1, 2) == 3
def test_raises():
with pytest.raises(ValueError, match='bad'):
parse('bad')
assert 0.1 + 0.2 == pytest.approx(0.3)
Fixtures
Fixtures are dependency-injected setup/teardown: code after yield is teardown. Scope (function/class/module/session) controls reuse. conftest.py shares fixtures; tmp_path and monkeypatch are built in.
@pytest.fixture
def client():
c = Client()
yield c
c.close()
def test_get(client):
assert client.get('/').status == 200
Parametrize, marks and monkeypatch
@pytest.mark.parametrize runs one test over many cases. skip/skipif/xfail mark expected outcomes. monkeypatch.setattr patches attributes; unittest.mock asserts calls. Select tests with pytest -k, -m, -x.
@pytest.mark.parametrize('x,expected', [(1, 1), (2, 4)])
def test_square(x, expected):
assert square(x) == expected
def test_env(monkeypatch):
monkeypatch.setenv('MODE', 'test')
Memory Management
Reference counting and cyclic GC
CPython frees an object when its refcount reaches 0, so cleanup is deterministic and files close promptly. Reference cycles need the generational cyclic GC, which runs on allocation thresholds. gc.collect() forces a pass; gc.disable() only when you control cycles.
import sys, gc
sys.getrefcount(obj) # one more than you expect (the argument)
gc.collect() # collect unreachable cycles
gc.get_threshold() # (700, 10, 10)
Finding leaks
Common leaks: module-level caches, closures and callbacks, unclosed resources, and __del__ inside cycles. Diagnose with tracemalloc snapshots, gc.get_objects, or objgraph.
import tracemalloc
tracemalloc.start()
# ... workload ...
snap = tracemalloc.take_snapshot()
for stat in snap.statistics('lineno')[:5]:
print(stat)
weakref and memory-friendly patterns
weakref.ref and WeakValueDictionary hold objects without keeping them alive — good for caches and observer lists. __slots__ removes the per-instance __dict__, and generators stream data instead of materializing lists.
import weakref
cache = weakref.WeakValueDictionary()
cache['k'] = Big() # entry disappears when no other refs remain
Common Gotchas
List comprehension scope
In Python 3 a comprehension's loop variable does not leak into the enclosing scope (unlike Python 2). A walrus := inside a comprehension can still bind outward.
[x for x in range(5)]
# x is NameError here in Py3
Modifying list while iterating
Iterating and mutating the same list skips elements. Iterate over a copy (lst[:]) or build a new list.
# bug
for x in lst:
if cond(x): lst.remove(x)
# fix
for x in lst[:]:
if cond(x): lst.remove(x)
Mutating a dict while iterating
Adding or removing keys during iteration raises RuntimeError: dictionary changed size during iteration. Iterate over list(d) or build a new dict.
for k in list(d):
if d[k] < 0: del d[k]
# or:
d = {k: v for k, v in d.items() if v >= 0}
Mutable class attributes
Class attributes are shared across instances, so a mutable class attribute (list/dict) is shared state — a bug. Initialize mutable state in __init__.
class A:
items = [] # shared across all instances!
def __init__(self):
self.items = [] # per-instance
Name resolution LEGB
Local, Enclosing, Global, Built-in. Assignment makes a name local for the whole function, which causes UnboundLocalError if it is read first. Use global/nonlocal to rebind an outer name.
x = 10
def f():
print(x) # UnboundLocalError: x assigned below
x = 5
Bare except and exception handling
Avoid bare except (it also catches SystemExit and KeyboardInterrupt). Catch Exception. Use finally for cleanup, else for the no-exception path, and never swallow errors silently.
try:
...
except Exception as e:
log(e)
else:
success()
finally:
cleanup()
Banker's rounding
round() uses round-half-to-even: round(2.5) is 2 and round(3.5) is 4. String formatting rounds the same way. Use Decimal with ROUND_HALF_UP for financial rounding.
round(2.5) # 2
round(3.5) # 4
f'{2.5:.0f}' # '2'
from decimal import Decimal, ROUND_HALF_UP
Decimal('2.5').quantize(Decimal('1'), rounding=ROUND_HALF_UP) # 3
Negative floor division and modulo
// floors toward negative infinity and % follows the sign of the divisor, so -7 // 2 is -4 and -7 % 2 is 1. Use math.fmod or int(a / b) for C-style truncation.
-7 // 2 # -4
-7 % 2 # 1
divmod(-7, 2) # (-4, 1)
What's new in Python (3.12 → 3.14)
What is free-threaded Python, and what's its status in 3.14?
A CPython build without the GIL (python3.14t), so threads run Python bytecode truly in parallel on multiple cores. Experimental in 3.13, officially supported (not default) in 3.14 (PEP 779). Single-thread overhead is roughly 5-10%. C extensions must declare support.
python3.14t app.py # free-threaded build, GIL disabled
# PEP 779: officially supported tier in 3.14, still not the default build
GIL — when do threads already help in normal CPython?
For I/O-bound work (the GIL is released during blocking I/O) and C libraries that release it (NumPy, hashing). For CPU-bound pure Python use multiprocessing, the free-threaded build, or subinterpreters.
threads -> I/O-bound, or C libs that release the GIL (NumPy, hashing)
multiprocessing -> CPU-bound pure Python
python3.14t -> CPU-bound threads without separate processes
Template strings (3.14, PEP 750)?
t"Hello {name}" evaluates to a Template object (static strings + interpolations), not a str. Libraries can safely escape the values: SQL params, HTML, shell. Like f-strings but for safe processing.
t"Hello {name}" # Template object, NOT a str
# library decides escaping
sql = db.sql(t"SELECT * FROM users WHERE name = {name}")
New generics syntax (3.12, PEP 695)?
def first[T](xs: list[T]) -> T: ..., class Box[T]: ..., type Pair[T] = tuple[T, T]. No more TypeVar boilerplate.
def first[T](xs: list[T]) -> T: ...
class Box[T]:
def __init__(self, item: T) -> None: ...
type Pair[T] = tuple[T, T]
Deferred annotations in 3.14 (PEP 649/749)?
Annotations are evaluated lazily when accessed (annotationlib), so forward references work without quotes or from __future__ import annotations, and imports get faster.
def f(x: LaterDefined) -> None: ... # no quotes, no __future__ import
import annotationlib
annotationlib.get_annotations(f) # evaluated on access
Other 3.14 additions to mention?
concurrent.interpreters (multiple interpreters in the stdlib, PEP 734), compression.zstd, except A, B: without parentheses (PEP 758), SyntaxWarning for return in finally (PEP 765), colourful REPL and better error messages.
from concurrent import interpreters # PEP 734
import compression.zstd
except ValueError, TypeError: # PEP 758, no parens needed
...
f-string changes in 3.12 (PEP 701)?
You can reuse the same quotes inside (f"{d["key"]}"), add backslashes and comments, write multi-line expressions. The f-string is now part of the formal grammar.
f"{d["key"]}" # same quotes nested, allowed in 3.12+
f"{x:\>10}" # backslashes allowed
f"""{ \n a + b \n }""" # multi-line expressions + comments
Python 3.13 headline features?
Experimental free-threaded build, experimental JIT (--enable-experimental-jit), new interactive REPL (multi-line editing, colour), copy.replace(), removal of the "dead batteries" modules (PEP 594).
python3.13 --enable-experimental-jit app.py
import copy
copy.replace(point, x=5) # dataclass/namedtuple style replace