The snippet library.
Small, practical examples. Search by task or narrow things down below.
Avoid a shared mutable default argument
Python: Create a fresh list inside the function when the optional argument is omitted.
Python✓ Tested
Cache repeated pure function calls
Python: Use lru_cache to avoid recomputing results for identical hashable arguments.
Python✓ Tested
Capture a successful child-process result
Python: Run an argument list without a shell and check the return code.
Python✓ Tested
Collect independent asynchronous results
Python: Use asyncio.gather to await multiple coroutines while preserving input order.
Python✓ Tested
Handle an expected child-process failure
Python: Catch CalledProcessError when check=True reports a nonzero exit status.
Python✓ Tested
Parse a typed command-line option
Python: Use argparse to validate and convert an integer option.
Python✓ Tested
Preconfigure some function arguments
Python: Use partial to produce a callable with selected arguments already bound.
Python✓ Tested
Raise and catch a domain-specific exception
Python: Give a validation failure its own exception type so callers can handle it narrowly.
Python✓ Tested
Run cleanup around a custom context
Python: Use try/finally inside a contextmanager so cleanup runs even on failure.
Python✓ Tested
Yield values on demand
Python: Use a generator to produce a sequence without storing all intermediate values.
Python✓ Tested