Skip to main content Brad's PyNotes

Stdlib Tour 2 Tutorial

TL;DR

The second stdlib tour covers professional-grade modules: precise decimal arithmetic, efficient data structures, logging, threading, and binary data handling.

Interesting!

The decimal module can represent exact monetary values without floating-point errors - crucial for financial applications where precision matters!

Output Formatting

python code snippet start

import reprlib
import pprint
import textwrap

# Abbreviated displays for large data
large_set = set('supercalifragilisticexpialidocious')
print(reprlib.repr(large_set))  # {'a', 'c', 'd', 'e', 'f', 'g', ...}

# Pretty printing with formatting
data = [('Pam', 3), ('Karen', 7), ('Jim', 4)]
pprint.pprint(data, width=30)

# Text wrapping
doc = """The wrap() method is just like fill() except that it returns
a list of strings instead of one big string with newlines to separate
the wrapped lines."""
print(textwrap.fill(doc, width=40))

python code snippet end

Precise Decimal Arithmetic

python code snippet start

from decimal import Decimal, getcontext

# Exact decimal representation
print(Decimal('0.70') * Decimal('1.05'))  # 0.7350 (exact)
print(0.70 * 1.05)                        # 0.7350000000000001 (float error)

# High precision calculations
getcontext().prec = 36
print(Decimal(1) / Decimal(7))  # 36 digits of precision

# Financial calculations
tax_rate = Decimal('0.0825')
cost = Decimal('15.99')
total = cost * (1 + tax_rate)
print(f"Total: ${total:.2f}")

python code snippet end

Efficient Data Structures

python code snippet start

from collections import deque
import bisect
import heapq

# Double-ended queue
d = deque(['task1', 'task2', 'task3'])
d.appendleft('urgent_task')  # Add to front
d.pop()                      # Remove from back

# Maintain sorted list
scores = [60, 70, 80, 90]
bisect.insort(scores, 85)  # [60, 70, 80, 85, 90]

# Priority queue
tasks = []
heapq.heappush(tasks, (1, 'high priority'))
heapq.heappush(tasks, (3, 'low priority'))
heapq.heappush(tasks, (2, 'medium priority'))
priority, task = heapq.heappop(tasks)  # Gets highest priority

python code snippet end

Professional Logging

python code snippet start

import logging

# Configure logging
logging.basicConfig(level=logging.INFO, 
                   format='%(asctime)s - %(levelname)s - %(message)s')

# Different log levels
logging.debug('Detailed debug information')
logging.info('General information')
logging.warning('Warning message')
logging.error('Error occurred')
logging.critical('Critical error!')

# Log to file
logging.basicConfig(filename='app.log', level=logging.INFO)

python code snippet end

Binary Data Handling

python code snippet start

import struct

# Pack data into binary format
data = struct.pack('HHI', 1, 2, 3)  # 2 unsigned shorts, 1 unsigned int
print(data)  # b'\x01\x00\x02\x00\x03\x00\x00\x00'

# Unpack binary data
values = struct.unpack('HHI', data)
print(values)  # (1, 2, 3)

# Useful for file format parsing
with open('binary_file.dat', 'rb') as f:
    header = struct.unpack('4sHH', f.read(8))  # 4-char string, 2 shorts

python code snippet end

Compact Arrays

python code snippet start

from array import array

# Memory-efficient numeric arrays
numbers = array('i', [1, 2, 3, 4, 5])  # integer array
print(numbers.itemsize)  # 4 bytes per item

# Much more efficient than lists for numeric data
floats = array('f', [1.1, 2.2, 3.3])  # float array

python code snippet end

These modules bridge the gap between basic Python and professional application development - providing the tools needed for robust, efficient programs!

Reference: Brief Tour of the Standard Library — Part II