Python 3 Standard Library: Key Modules and API References
The Python 3 standard library consists of pre-installed modules and classes that provide tools for common tasks, analogous to standard libraries in C, Java, and other languages. These modules streamline development by offering ready-to-use solutions for specialized problems.
Core Modules
- os: Interacts with the operating system, enabling file/directory operations (creation, movement, deletion) and environment variable access.
- sys: Provides access to Python interpreter and system-specific parameters, including version info, paths, and I/O streams (stdin/stdout/stderr).
- time: Offers basic time manipulation functions (current time rertieval, formatting, timing).
- datetime: Advanced date/time handling with timezone support, duration calculations, and date arithmetic.
- random: Generates pseudorandom numbers (integers, floats, sequence selections).
- math: Mathematical functions (trigonometry, logarithms, exponents) and constants.
- re: Regular expression engine for complex text search, replacement, and splitting.
- json: Encodes Python objects to JSON and decodes JSON to Python data structures.
- urllib: Facilitates web interactions, including URL handling, file downloads, and HTTP requests.
Perfer import module over from module import * to avoid namespace pollution. Use built-in dir() and help() to explore module/function capabilities.
Practical Exapmles
# List directory contents using os.scandir (more efficient than listdir)
import os
with os.scandir('.') as entries:
py_files = [entry.name for entry in entries if entry.name.endswith('.py')]
# Find files matching pattern with glob
import glob
script_files = glob.glob('*.py')
# Extract words starting with 'b' using regex
import re
text = "blue bird builds big nests"
b_words = re.findall(r'\bb\w*', text) # Returns ['blue', 'bird', 'builds', 'big']
# Random selection from a list
import random
fruits = ['mango', 'kiwi', 'orange']
selected_fruit = random.choice(fruits)
# Date/time operations with datetime
import datetime
current_dt = datetime.datetime.now() # Current timestamp
current_day = datetime.date.today() # Today's date
fmt_dt = current_dt.strftime("%Y/%m/%d %H:%M") # Formatted string (e.g., "2023/10/05 14:30")
Internet Access
For network communication, use urllib.request to fetch data from URLs and smtplib to send emails programmatically.
Data Compression
Modules like zlib, gzip, bz2, zipfile, and tarfile handle common compression formats for archiving and data packaging.
Performence Measurement
Compare execution times of different approaches using the timeit module. For example, swapping variables via tuple unpacking outperforms temporary assignment:
from timeit import Timer
# Traditional swap with temp variable
time_temp = Timer('temp = x; x = y; y = temp', 'x=10; y=20').timeit(number=1000000)
# Tuple unpacking swap
time_unpack = Timer('x, y = y, x', 'x=10; y=20').timeit(number=1000000)
Testing Frameworks
- doctest: Validates code via embedded docstrings. Example:
def compute_mean(nums):
"""Calculate arithmetic mean of a number list.
>>> compute_mean([15, 25, 35])
25.0
"""
return sum(nums) / len(nums)
import doctest
doctest.testmod() # Auto-run embedded tests
- unittest: Structured testing with test cases in separate files:
import unittest
def compute_mean(nums):
return sum(nums) / len(nums)
class TestMathOps(unittest.TestCase):
def test_mean_calculation(self):
self.assertEqual(compute_mean([15, 25, 35]), 25.0)
self.assertAlmostEqual(compute_mean([1, 2, 3]), 2.0, places=1)
self.assertRaises(ZeroDivisionError, compute_mean, [])
if __name__ == '__main__':
unittest.main()
API documentation links provide detailed referecnes for all standard library modules.