11. Useful Standard Library

Grab-bag of batteries-included modules you’ll reach for frequently.

Question: Name some useful modules in the Python standard library.

Answer:

  • collections: Provides advanced data structures like Counter (for counting hashable objects), defaultdict (a dictionary that provides a default value for missing keys), and deque (a double-ended queue).

  • datetime: For working with dates and times.

  • json: For parsing and generating JSON data.

  • os and pathlib: For interacting with the operating system and file paths.

  • random: For generating random numbers.

  • itertools: Building blocks for efficient loops, e.g., chain, cycle, groupby.

  • logging: Configurable application logging; prefer over print in real apps.

  • functools: Higher-order functions like lru_cache (memoization), partial (pre-fill arguments), and wraps (preserve metadata in decorators).

  • csv: Read and write CSV files interoperably.

  • statistics: Basic stats like mean, median, stdev.

  • contextlib: Tools for context managers, e.g., contextmanager, ExitStack, suppress.

  • re: Regular expressions for text parsing.

  • typing: Type hints like TypedDict, Protocol, Literal.