Introduction to Python Standard Library Modules: collections, heapq, bisect, array, weakref, and pprint
This article provides a concise overview of several Python standard‑library modules—including collections, heapq, bisect, array, weakref, and pprint—explaining their main features, typical use‑cases, and offering clear code examples for each.
1. collections module
The collections module offers specialized container datatypes such as Counter for counting hashable objects, defaultdict which automatically creates default values for missing keys, and deque for fast double‑ended queue operations.
from collections import Counter
li = ["Dog", "Cat", "Mouse", 42, "Dog", 42, "Cat", "Dog"]
a = Counter(li)
print(a) # Output: Counter({'Dog': 3, 42: 2, 'Cat': 2, 'Mouse': 1}) from collections import defaultdict
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
print(d) # Output: defaultdict(list, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}) from collections import deque
d = deque("ghi")
d.append('j')
d.appendleft('f')
print(d) # Output: deque(['f', 'g', 'h', 'i', 'j'])2. heapq module
The heapq module implements heap queue algorithms, also known as priority queues, with a default min‑heap where each parent node is less than or equal to its children.
import heapq
heap = []
heapq.heappush(heap, (5, 'write code'))
heapq.heappush(heap, (7, 'release product'))
heapq.heappush(heap, (1, 'write spec'))
print(heapq.heappop(heap)) # Output: (1, 'write spec')3. bisect module
The bisect module provides binary search and insertion utilities for sorted lists, enabling efficient location of insertion points.
import bisect
sorted_list = [1, 2, 4, 5]
position = bisect.bisect(sorted_list, 3)
print(position) # Output: 24. array module
The array module supplies a compact array type that stores only homogeneous numeric values, offering memory efficiency compared to regular Python lists.
import array
arr = array.array('i', [1, 2, 3, 4])
print(arr) # Output: array('i', [1, 2, 3, 4])5. weakref module
Weak references allow objects to be referenced without preventing their garbage collection, useful for caches, breaking reference cycles, and monitoring object finalization. Key components include weakref.ref , weakref.proxy , WeakKeyDictionary , WeakValueDictionary , WeakSet , and finalize .
Example of creating a weak reference and checking its value after the original object is deleted:
import weakref
class MyClass:
pass
obj = MyClass()
r = weakref.ref(obj)
print(r()) # Output: <__main__.MyClass object at ...>
del obj # Remove strong reference
print(r()) # Output: NoneExample of registering a callback to be invoked when the object is about to be collected:
def callback(ref):
print("Object has been garbage collected.")
obj = MyClass()
r = weakref.ref(obj, callback)
del obj # Triggers callback and prints the messageUsing weak references correctly can improve memory management and application stability.
6. pprint module
The pprint module provides “pretty‑print” capabilities that format complex nested data structures for easier reading.
import pprint
data = {"key": ["value1", "value2"]}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(data)Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.