Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · Python · Chapter 11 / 16

Programming learning path

Standard library tour

collections, itertools, functools, datetime, os/sys and logging.

The collections module: Counter, defaultdict, deque

Specialized container types that replace common manual bookkeeping patterns with a single import.

Counter(iterable) tallies hashable items and exposes .most_common(n) for ranked frequency results, replacing a manual dict-and-increment loop. defaultdict(factory) behaves like a normal dict except that reading a missing key first creates it using factory() instead of raising KeyError, which removes the need for an if key not in d: check before every first insertion into a nested structure. deque (double-ended queue) supports O(1) appends and pops from either end, unlike a plain list, which makes it the right choice for queues, sliding windows, and any "remove from the front" pattern.

Key points

  • Counter(iterable).most_common(n) ranks item frequency without a manual loop
  • defaultdict(factory) auto-creates missing keys, removing manual existence checks
  • deque gives O(1) append/pop from both ends, unlike list's O(n) at the front

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Ranking word frequency, grouping words by length without existence checks, and a fixed-size recent-history deque.

Common pitfalls

  • defaultdict(list)["missing_key"] silently creates the key just by reading it, which can hide typos
  • A plain list used as a queue with .pop(0) is O(n) per removal; deque.popleft() is O(1)

Practice exercise

Given a list of HTTP status codes from a log, use Counter to find the 3 most common ones, and use defaultdict to group the codes by their first digit (2xx, 4xx, 5xx).

itertools and functools essentials

Lazy iterator composition and function-level tools that remove common loop and caching boilerplate.

From itertools: chain(a, b) walks multiple iterables as one lazy sequence, islice(it, n) lazily takes the first n items from any iterator (even an infinite one), and product(a, b) generates every combination pair without a nested loop. From functools: @lru_cache(maxsize=None) memoizes a pure function's results automatically keyed by its arguments, and partial(func, fixed_arg) pre-fills some of a function's arguments to create a simpler, specialized callable. Together these two modules replace a large share of hand-written looping and caching boilerplate with well-tested, efficient building blocks.

Key points

  • chain() and islice() compose and bound iterators lazily, without materializing full lists
  • product(a, b) replaces a nested for loop for generating every combination pair
  • @lru_cache memoizes results; partial() pre-fills some arguments of a function

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Generating combinations with product(), memoizing recursive Fibonacci, and pre-filling an argument with partial().

Common pitfalls

  • @lru_cache on a function with mutable-argument inputs (like a list) raises TypeError, since arguments must be hashable
  • @lru_cache silently returns stale results if the function has side effects or depends on external state

Practice exercise

Use itertools.product to generate every possible 4-digit PIN combination lazily (do not materialize the full list), and use @lru_cache to speed up a slow recursive function of your choice.

Working with dates and times

datetime objects, formatting with strftime, parsing with strptime, and the naive-versus-aware distinction.

datetime.now() returns the current local time as a naive datetime (no timezone attached); datetime.now(timezone.utc) returns an aware one anchored to UTC. .strftime("%Y-%m-%d") formats a datetime into a string using format codes, while datetime.strptime(text, "%Y-%m-%d") does the reverse, parsing a string into a datetime according to the same code system. Subtracting two datetime objects produces a timedelta, representing a duration, which itself supports arithmetic like adding days to a date. Subtracting a naive datetime from an aware one, or ordering them with </>, raises TypeError rather than silently guessing a timezone — but equality is allowed: a naive and an aware datetime simply compare as unequal, since Python has no basis to treat them as the same instant.

Key points

  • datetime.now() is naive; datetime.now(timezone.utc) is aware and anchored to UTC
  • strftime formats a datetime to text; strptime parses text into a datetime
  • Subtracting two datetimes gives a timedelta; subtracting or ordering naive vs. aware raises TypeError, but == just compares them unequal

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Computing a deadline a week from now, formatting it for display, and parsing a date string back into a datetime.

Common pitfalls

  • Ordering or subtracting a naive datetime.now() against an aware value from an API raises TypeError (== would just be False)
  • Assuming datetime.now() is UTC is wrong on most systems — it is local time unless you pass timezone.utc

Practice exercise

Write a function that takes a birthdate string in "YYYY-MM-DD" format, parses it, and returns the person's age in whole years as of today.

os and sys for environment and runtime info

os talks to the operating system (environment variables, processes); sys exposes interpreter-level state.

os.environ is a dict-like mapping of the process's environment variables, commonly read with os.environ.get("API_KEY") to configure a program without hardcoding secrets or environment-specific values into source code. os.getcwd(), os.listdir() and related functions expose filesystem information (though pathlib is preferred for path manipulation itself). sys.argv is the list of command-line arguments the process was invoked with; sys.argv[0] commonly holds the script name when a script file is run, but its exact value depends on how Python was invoked — it is "-c" when using python -c, for instance. sys.exit(code) raises SystemExit rather than halting the process instantly — finally blocks still run, and the exception can even be caught — and it terminates the program with the given status once that SystemExit reaches the top of the main thread uncaught, commonly used to signal success (0) or failure (non-zero) to a calling shell or CI pipeline.

Key points

  • os.environ.get("NAME") reads an environment variable without hardcoding secrets
  • sys.argv holds command-line arguments; sys.argv[0]'s exact value depends on how Python was invoked
  • sys.exit(code) raises SystemExit, which normally terminates the program with that status once uncaught

Code

import os, sys

api_key = os.environ.get("API_KEY")
if not api_key:
    print("Missing API_KEY environment variable", file=sys.stderr)
    sys.exit(1)

print("Arguments:", sys.argv[1:])

Reading required configuration from the environment and exiting with an error status if it's missing.

Common pitfalls

  • os.environ["NAME"] raises KeyError if missing; use .get() with a default or explicit check instead
  • Forgetting sys.argv[0] is the script name itself, so real arguments start at index 1

Practice exercise

Write a small CLI script that reads a required OUTPUT_DIR environment variable, exits with status 1 and an error message on stderr if it's missing, and otherwise prints the command-line arguments it received.

Structured diagnostic output with logging

logging replaces print() debugging with leveled, configurable, and production-appropriate diagnostics.

logging.getLogger(__name__) creates a logger scoped to the current module, and calling .debug(), .info(), .warning(), .error() or .critical() on it records a message at that severity level. logging.basicConfig(level=logging.INFO) sets a minimum level for the whole program — messages below that level are silently skipped, so verbosity can be tuned per environment without touching the calls themselves. A log record carries structured metadata such as the logger name, severity and event time internally, but it is the configured formatter that decides which fields actually get displayed — the default basicConfig() format shows level, logger name and message, with no timestamp unless the format string includes something like %(asctime)s. Unlike print(), log calls can be routed to a file or remote system instead of only the console, and filtered by severity without touching the calls themselves.

Key points

  • getLogger(__name__).info/warning/error() records a message at that severity level
  • basicConfig(level=...) sets the minimum level shown, tunable per environment
  • Log records carry rich metadata, but the formatter decides what's shown — the default format has no timestamp

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Configuring a minimum log level and logging structured messages at different severities.

Common pitfalls

  • logger.info("value: " + str(x)) always builds the string even if INFO is filtered out; logger.info("value: %s", x) is lazier and cheaper
  • Calling basicConfig() again after the root logger already has handlers normally does nothing — pass force=True when a deliberate reconfiguration is actually needed

Practice exercise

Replace every print() call in a small script with appropriately-leveled logging calls (info for normal progress, warning for recoverable issues, error for failures), and configure the minimum level.

Source registry

5 chapter references
collections — Container datatypes

deque, defaultdict, Counter, namedtuple and ChainMap semantics

Python Software Foundation · Official reference
Source ↗
itertools — Functions creating iterators for efficient looping

Lazy iterator composition and memory-efficient looping patterns

Python Software Foundation · Official reference
Source ↗
functools — Higher-order functions and operations on callable objects

lru_cache, partial, wraps, reduce and singledispatch behavior

Python Software Foundation · Official reference
Source ↗
The Python Standard Library

Authoritative behavior for built-in types and standard library modules

Python Software Foundation · Official reference
Source ↗
logging — Logging facility for Python

Loggers, handlers, levels and structured diagnostic output

Python Software Foundation · Official reference
Source ↗