Overview of Useful Python Standard Library Modules with Example Code
This article introduces several essential Python standard library modules—including cmd, getpass, glob, pickle, shelve, codecs, functools, inspect, weakref, and xml.etree.ElementTree—providing brief descriptions and ready‑to‑run code examples that demonstrate their core functionalities.
cmd – provides a simple framework for building interactive command-line interpreters.
import cmd
class MyCmd(cmd.Cmd):
def do_greet(self, line):
print("Hello,", line)
def do_exit(self, line):
return True
MyCmd().cmdloop()getpass – allows secure password input without echoing to the screen and also supports retrieving the current username.
import getpass
user = getpass.getuser()
password = getpass.getpass()
print(f"Username: {user}")glob – finds file pathnames matching a specified pattern, similar to Unix shell pathname expansion.
import glob
files = glob.glob('*.txt') # find all .txt files in the current directory
print(files)pickle – implements serialization (pickling) and deserialization (unpickling) of Python object structures.
import pickle
data = {'key': 'value'}
with open('data.pkl', 'wb') as f:
pickle.dump(data, f) # serialize data to a fileshelve – offers a dictionary‑like persistent storage built on top of pickle.
import shelve
with shelve.open('mydata') as db:
db['key'] = 'value'codecs – provides support for encoding and decoding text files with various character encodings.
import codecs
with codecs.open('file.txt', 'r', encoding='utf-8') as file:
content = file.read()functools – supplies higher‑order functions such as decorators and partial function application; example shows an LRU‑cached recursive Fibonacci function.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)inspect – offers utilities to retrieve information about live objects, such as obtaining source code of a function.
import inspect
def my_function():
pass
print(inspect.getsource(my_function)) # get function source codeweakref – supports weak references to objects, helping with garbage collection and avoiding reference cycles.
import weakref
class MyClass:
pass
obj = MyClass()
r = weakref.ref(obj)
print(r()) # prints the referenced objectxml.etree.ElementTree – enables parsing and creation of XML data structures.
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
print(root.tag)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.