The snippet library.
Small, practical examples. Search by task or narrow things down below.
Advance a date by a number of days
Python: Use timedelta so month and year boundaries are handled automatically.
Python✓ Tested
Append a line to a file
Add a new line to the end of a text file without replacing its existing contents. Append mode also creates the file if it does not exist.
file✓ Tested
Avoid a shared mutable default argument
Python: Create a fresh list inside the function when the optional argument is omitted.
Python✓ Tested
Build a URL query string
Python: Use urlencode to percent-encode query parameter values correctly.
Python✓ Tested
Cache repeated pure function calls
Python: Use lru_cache to avoid recomputing results for identical hashable arguments.
Python✓ Tested
Calculate a simple total
Python: Multiply a unit price by a quantity, then add a delivery fee.
Python✓ Tested
Calculate cumulative totals
Python: Use accumulate to retain the running sum after each input.
Python✓ Tested
Calculate the number of required pages
Python: Use integer arithmetic to round a nonnegative count up to a positive page size.
Python✓ Tested
Calculate with exact rational values
Python: Use Fraction for exact ratios rather than binary floating-point approximations.
Python✓ Tested
Call a library function
Python: Use a standard absolute-value function with a small negative number.
Python✓ Tested
Capture a successful child-process result
Python: Run an argument list without a shell and check the return code.
Python✓ Tested
Check whether all required keys exist
Python: Compare the required key set with a dictionary key view.
Python✓ Tested