Image by Author | Ideogram
If you’ve been working with Python, you’re likely familiar with its super extensive standard library that makes development efficient and straightforward. While popular modules like json, datetime, and re receive much attention, there’s a collection of lesser-known functions that often go unnoticed.
This article discusses some of those functions—what some may consider “useless” functions—except they’re not actually useless at all! These are those oddly specific, niche functions that might make you think, “Who would ever need that?” And then one day, you find yourself facing exactly the problem they were designed to solve.
So yeah, let’s go over these actually super helpful functions.
🔗 Link to the code on GitHub
1. textwrap.dedent() – Clean Up Those Messy Multi-line Strings
Have you ever written a multi-line string in Python and been frustrated by the indentation? If so, textwrap.dedent
is your friend!
Consider the following snippet that uses textwrap’s dedent
. This removes the extra indentation from a multi-line string that’s indented in your source code, resulting in clean text without the leading spaces.
import textwrap
def my_function():
# Without dedent, this would preserve all the leading spaces
description = textwrap.dedent("""
This is a multi-line string
that will have consistent indentation
regardless of how it's indented in the code.
Pretty neat, right?
""").strip()
return description
print(my_function())
Output:
This is a multi-line string
that will have consistent indentation
regardless of how it's indented in the code.
Pretty neat, right?
2. difflib.get_close_matches() – Fuzzy String Matching Made Easy
Sometimes you may need to find similarities between strings or implement a “did you mean?” feature. The get_close_matches
function from the difflib module has you covered.
Here are a couple of examples that show how to use this function:
import difflib
words = ["python", "javascript", "typescript", "ruby", "golang"]
search = "pythn"
matches = difflib.get_close_matches(search, words, n=3, cutoff=0.6)
print(f"Did you mean: matches")
Output:
The first example finds the closest match to “pythn” in a list of programming languages.
The second example shows how close matches to “typescript” include both “typescript” and “javascript”.
search = "typescript"
matches = difflib.get_close_matches(search, words)
print(f"Matches: matches")
Output:
['typescript', 'javascript']
This is especially useful when building for command-line tools, search features, or anywhere you need to account for typos or close matches.
3. uuid.uuid4() – Generate Guaranteed Unique IDs
If you need unique identifiers without setting up a database or worrying about collisions, you can use functions in the uuid module.
This creates a random UUID object that can be used as a unique identifier:
import uuid
# Generate a random UUID
random_id = uuid.uuid4()
print(f"Unique ID: random_id")
Output:
Unique ID: fc4c6638-9707-437b-83a1-76206b5f7191
The following example shows how to incorporate a UUID into a filename for guaranteed uniqueness:
# Use as string for filenames, database keys, etc.
filename = f"document-uuid.uuid4().pdf"
print(filename)
Output:
document-b5ccbe7a-fad9-4611-8163-be1015c634b9.pdf
These UUIDs (Universally Unique Identifiers) are practically guaranteed to be unique—even across different machines and times, making them perfect for generating IDs for files, database entries, or wherever else you need uniqueness.
4. shutil.get_terminal_size() – Responsive CLI Applications
Want your command-line application to adapt to the user’s terminal size? The get_terminal_size
function makes it easy.
Here’s how you can use it:
import shutil
columns, rows = shutil.get_terminal_size()
print(f"Your terminal is columns columns wide and rows rows tall")
# Create a horizontal divider that fits perfectly
print("-" * columns)
This gets the current terminal dimensions as columns and rows and creates a horizontal divider that precisely fits the width of the terminal.
Your terminal is 80 columns wide and 24 rows tall
--------------------------------------------------------------------------------
5. itertools.groupby() – Group Data Without Using Dictionaries
Need to group data by some key? itertools.groupby()
lets you do this efficiently.
In this example, we group a list of employees by their department after first sorting by department (required for groupby to work properly). Then we print each employee grouped by their department.
from itertools import groupby
from operator import itemgetter
# Sample data: (name, department)
employees = [
("Alice", "Engineering"),
("Bob", "Marketing"),
("Charlie", "Engineering"),
("Diana", "HR"),
("Evan", "Marketing"),
]
# Sort by department first (groupby works on consecutive items)
employees.sort(key=itemgetter(1))
# Group by department
for department, group in groupby(employees, key=itemgetter(1)):
print(f"\ndepartment Department:")
for name, _ in group:
print(f" - name")
Output:
Engineering Department:
- Alice
- Charlie
HR Department:
- Diana
Marketing Department:
- Bob
- Evan
6. collections.ChainMap – Merge Dictionaries Without the Overhead
Need to search through multiple dictionaries? ChainMap
lets you look through them in order without actually merging them.
Note: This is not a function but still a useful class in the collections module in the Python standard library.
Here’s a practical example:
from collections import ChainMap
defaults = "theme": "dark", "language": "en", "timeout": 30
user_settings = "theme": "light"
session_settings = "timeout": 60
# Create a combined view of all settings
settings = ChainMap(session_settings, user_settings, defaults)
print(settings["theme"])
print(settings["language"])
print(settings["timeout"])
This creates a view of multiple dictionaries that looks up values in order without merging the dictionaries, showing how settings from different sources can be prioritized.
Output:
7. os.path.commonpath() – Find Shared Directory Paths
Ever needed to find the common directory between multiple file paths? You can use path.commonpath
from the os module to do exactly that.
The following code identifies the longest common directory path from a list of file paths, useful for finding the base directory of a group of files:
import os.path
paths = [
"/home/user/documents/work/report.pdf",
"/home/user/documents/personal/taxes.xlsx",
"/home/user/documents/work/presentation.pptx"
]
common = os.path.commonpath(paths)
print(f"Common directory: common")
Output:
Common directory: /home/user/documents
As seen, this function is super handy for tasks like finding a common root directory for a set of files or building relative paths.
Wrapping Up
As we’ve seen, Python’s standard library contains several specialized functions that, while not commonly used, offer elegant solutions to specific problems.
Next time you’re writing a complex function to handle something that feels like a common problem, take a moment to check if the standard library already has a solution!
What’s your favorite lesser-known Python standard library function? Let me know in the comments, and I’ll compile more of these useful functions in a future post. Until then, happy coding!
Bala Priya C is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she’s working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.