Advanced Python technique
- User
Advanced Python technique
- Assistant
Hey there! “Advanced Python techniques” can mean a ton of different things, depending on what you’re building and what parts of the language you’ve already mastered. Below is a quick-fire tour of some power-user features. Skim the list, see what catches your eye, and let me know which topics you’d like to dive into next (happy to zoom in, bench-test code, or give real-world examples). 🚀
1. Decorators (incl. parameterized & class decorators)
from functools import wraps def retry(times=3): def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): for attempt in range(times): try: return fn(*args, **kwargs) except Exception as exc: if attempt == times - 1: raise return wrapper return decorator @retry(times=5) def flaky_io(): ...Why it’s advanced
• Adds behavior (logging, caching, permission checks) without touching the original code.
• Parameterized decorators = extra flexibility.
• Works on classes too: register plugins, enforce singleton, etc.
2. Context Managers Beyond
with open(...)a. Custom class-based
class timed_block: def __enter__(self): self.start = time.perf_counter() def __exit__(self, exc_type, exc, tb): print(f"Δt = {time.perf_counter() - self.start:.4f}s")b. Generator-based (
contextlib.contextmanager)from contextlib import contextmanager @contextmanager def db_session(engine): conn = engine.connect() try: yield conn conn.commit() finally: conn.close()Why it’s advanced
• Clean up resources safely; compose them; makes try/finally vanish.
• You can even nest & combine multiple managers usingcontextlib.ExitStack.
3. Descriptors (the machinery behind
property,@classmethod, etc.)class Positive: def __set_name__(self, owner, name): self.private_name = '_' + name def __get__(self, obj, owner): return getattr(obj, self.private_name) def __set__(self, obj, value): if value <= 0: raise ValueError("Must be > 0") setattr(obj, self.private_name, value) class Account: balance = Positive() acc = Account() acc.balance = 50 # OK acc.balance = -10 # 💥 ValueErrorWhy it’s advanced
• Gives you property-like control but reusable across many classes.
• Underpins ORMs (e.g., SQLAlchemy columns), validators (Pydantic), etc.
4. Metaclasses (classes that create classes)
class AutoRepr(type): def __new__(mcls, name, bases, ns): def __repr__(self): attrs = ", ".join(f"{k}={v!r}" for k, v in self.__dict__.items()) return f"{name}({attrs})" ns.setdefault('__repr__', __repr__) return super().__new__(mcls, name, bases, ns) class Model(metaclass=AutoRepr): pass class User(Model): def __init__(self, name, age): self.name, self.age = name, age print(User("Ada", 32)) # → User(name='Ada', age=32)Why it’s advanced
• Alters class creation (ORM base classes, Django models).
• Can enforce interfaces, auto-register subclasses for plugins, etc.
5.
async/await, event loops & concurrency primitivesimport asyncio, aiohttp async def fetch(session, url): async with session.get(url) as r: return await r.text() async def main(): urls = ['https://example.com', 'https://python.org'] async with aiohttp.ClientSession() as sess: pages = await asyncio.gather(*(fetch(sess, u) for u in urls)) print(len(pages)) asyncio.run(main())Why it’s advanced
• Non-blocking I/O = orders-of-magnitude speed-ups for network/file heavy apps.
• Need to juggle tasks, cancellations, timeouts & back-pressure.
6. Typing power moves:
Protocol,TypeVar,ParamSpecfrom typing import Protocol, runtime_checkable, TypeVar T = TypeVar("T") @runtime_checkable class SupportsLess(Protocol[T]): def __lt__(self, other: T) -> bool: ... def minmax(a: SupportsLess[T], b: T) -> tuple[T, T]: return (a, b) if a < b else (b, a)Why it’s advanced
• Structural typing (duck typing at type-checker level).
• Write library code that’s both flexible and statically safe.
7.
functools.singledispatch&singledispatchmethodfrom functools import singledispatch @singledispatch def to_json(obj): raise TypeError(f"Unsupported: {type(obj)}") @to_json.register def _(obj: set): return list(obj) @to_json.register def _(obj: datetime.date): return obj.isoformat()Why it’s advanced
• Function overloading by argument type without heritage from C++/Java.
• Extensible by downstream users (great for plugins).
8. Memory-level performance hacks
•
array,memoryview,struct,ctypes— zero-copy slices.
•numpy.ndarrayexposes the buffer protocol: operate on raw memory.
• Cython /mypycto compile hot-spots.
•multiprocessing.shared_memoryfor truly huge data sets across processes.
9. Introspection & dynamic code generation
import inspect def debug(fn): sig = inspect.signature(fn) def wrapper(*args, **kwargs): bound = sig.bind(*args, **kwargs) print(f"[CALL] {fn.__name__}{bound.args, bound.kwargs}") result = fn(*args, **kwargs) print(f"[RET ] {result!r}") return result return wrapperWhy it’s advanced
• Build debuggers, RPC stubs, auto-docs.
• Modify functions at runtime or write class factories.
10. Advanced
dataclasses@dataclass(slots=True, frozen=True, kw_only=True) class Vector3: x: float y: float z: floatTricks
•slots=True= memory win, attribute lookup faster.
•frozen=True+__hash__for dictionary keys.
• Post-init validation, default factory lambdas, etc.
Where to go from here?
- Let me know which topics (or others) you want a deeper dive on.
- Share the project or pain point you’re tackling, and I’ll recommend the “just-enough” advanced magic (sometimes the fanciest trick is not the right one!).
- Prefer hands-on? We can craft a mini-project or “kata” around the technique.
What’s next? 😊
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.