Core Module
12 min forge

Python Standard Library Favorites

Why Python is "Batteries Included". Essential modules every engineer must know.

Python Standard Library Favorites

πŸ›‘οΈ What is the Standard Library?

Python's "Batteries Included" philosophy means it comes with a vast collection of modules ready to solve common tasks without installing external packages.

⏰ When to Use

  • Data Serialization: json for APIs, pickle for Python-specific binary serializing.
  • File System: os and the modern pathlib for file/directory manipulation.
  • Concurrency: threading, multiprocessing, and asyncio.
  • Utilities: collections (namedtuple, deque, Counter), itertools (efficient looping), and functools (decorators/wrappers).

πŸ“Š Complexity & Performance

  • pathlib over os.path: pathlib offers an object-oriented approach which is more readable and less error-prone.
  • collections.deque: Provides $O(1)$ appends and pops from both ends, compared to list's $O(N)$ for popping from the front.
  • itertools: Generators in itertools are memory-efficient because they process items one-by-one rather than loading entire lists into RAM.

πŸ’» Code Example: Utility Power

python Standard
import json from pathlib import Path from collections import Counter, namedtuple # 1. Modern Path handling logs_dir = Path("logs/daily") logs_dir.mkdir(parents=True, exist_ok=True) # 2. Advanced Collections Point = namedtuple('Point', ['x', 'y']) p = Point(10, 20) # 3. Frequency Identification text = "forge your path with the interview forge" counts = Counter(text.split()) print(counts.most_common(1)) # [('forge', 2)] # 4. JSON Serialization data = {"status": "cracked", "score": 99.5} json_string = json.dumps(data)

⚠️ Interview Pitfalls

  1. pickle Security: Never unpickle data from an untrusted source, as it can execute arbitrary code.
  2. os vs subprocess: For running shell commands, subprocess.run() is the modern, secure standard; avoid os.system().
  3. Deep vs Shallow Copy: Know the copy module (copy.copy() vs copy.deepcopy()) for handling nested objects.
  4. datetime timezone management: Always prefer aware datetimes (with pytz or Python 3.9's zoneinfo) over naive ones to avoid daylight saving bugs.