FIND YOUR NEXT FEW LINES

The snippet library.

Small, practical examples. Search by task or narrow things down below.

10 snippets foundClear filters
PythonFunctions & error handling

Avoid a shared mutable default argument

Python: Create a fresh list inside the function when the optional argument is omitted.

Python✓ Tested
PythonFunctions & error handling

Cache repeated pure function calls

Python: Use lru_cache to avoid recomputing results for identical hashable arguments.

Python✓ Tested
PythonFunctions & error handling

Capture a successful child-process result

Python: Run an argument list without a shell and check the return code.

Python✓ Tested
PythonFunctions & error handling

Collect independent asynchronous results

Python: Use asyncio.gather to await multiple coroutines while preserving input order.

Python✓ Tested
PythonFunctions & error handling

Handle an expected child-process failure

Python: Catch CalledProcessError when check=True reports a nonzero exit status.

Python✓ Tested
PythonFunctions & error handling

Parse a typed command-line option

Python: Use argparse to validate and convert an integer option.

Python✓ Tested
PythonFunctions & error handling

Preconfigure some function arguments

Python: Use partial to produce a callable with selected arguments already bound.

Python✓ Tested
PythonFunctions & error handling

Raise and catch a domain-specific exception

Python: Give a validation failure its own exception type so callers can handle it narrowly.

Python✓ Tested
PythonFunctions & error handling

Run cleanup around a custom context

Python: Use try/finally inside a contextmanager so cleanup runs even on failure.

Python✓ Tested
PythonFunctions & error handling

Yield values on demand

Python: Use a generator to produce a sequence without storing all intermediate values.

Python✓ Tested