Photo by the author Ideogram
Python’s standard library has several tools that can transform your code from clumsy and talkative into elegant and capable. Among them, functooloty and iTeToototot modules are often very useful for non -trivial tasks.
Today we will look at seven necessary tools – functions and decorators – from these modules that will make your Python code better.
Let’s start.
1. functools.lru_cache
You can exploit @lru_cache Decorator for buffering function results and to avoid repeating high-priced operations.
Here is an example:
from functools import lru_cache
@lru_cache(maxsize=128)
def fetch_user_data(user_id):
# Steep database call
return database.get_user(user_id)
# First call hits database, subsequent calls exploit cache
user = fetch_user_data(123) # Database call
user = fetch_user_data(123) # Returns cached result
How it works: @lru_cache Stock decorators results in memory. When fetch_user_data(123) It is called again, returns a buffered result instead of hitting the database. maxsize=128 Maintains 128 latest results.
2. itertools.chain
To process many iterables as one continuous stream, you can exploit chain.from_iterable() from the iTools module.
Let’s take an example:
from itertools import chain
# Process multiple log files as one stream
error_logs = ['app.log', 'db.log', 'api.log']
all_lines = chain.from_iterable(open(f) for f in error_logs)
error_count = sum(1 for line in all_lines if 'ERROR' in line)
How it works: chain.from_iterable() It takes a lot of iterable and creates one continuous stream. He reads one line at once.
3. functools.partial
Partial functions in Python are very helpful when you need to create specialized versions of the function. Which means you want to create versions of functions with some arguments already established partial from the Functools module.
Here is an example of a partial function:
from functools import partial
import logging
def log_event(level, component, message):
logging.log(level, f"[{component}] {message}")
# Create specialized loggers
auth_error = partial(log_event, logging.ERROR, 'AUTH')
db_info = partial(log_event, logging.INFO, 'DATABASE')
# Tidy usage
auth_error("Login failed for user")
db_info("Connection established")
How it works: partial He creates a fresh function with some filled arguments. In the example, auth_error is imperative log_event With a level and component already set, so you just need to provide a message.
4. itertools.combinations
When you need to generate all possible combinations of elements for testing or optimizing, you can exploit combinations from the iTools module.
Consider the following example:
from itertools import combinations
features = ['cache', 'compression', 'cdn']
# Test all pairs of features
for combo in combinations(features, 2):
performance = test_feature_combo(combo)
print(f"{combo}: {performance}ms")
How it works: combinations(features, 2) It generates all possible couples from the list. It creates combinations on demand without storing them all in memory, making it capable for huge data sets.
5. functools.singledispatch
. @singledispatch The Functools decorator can assist perform functions that work differently depending on the input type.
Look at the following code fragment:
from functools import singledispatch
from datetime import datetime
@singledispatch
def format_data(value):
return str(value) # Default
@format_data.register(datetime)
def _(value):
return value.strftime("%Y-%m-%d")
@format_data.register(list)
def _(value):
return ", ".join(str(item) for item in value)
# Automatically picks the right formatter
print(format_data(datetime.now())) # this outputs "2025-06-27"
print(format_data([1, 2, 3])) # this outputs "1, 2, 3"
How it works: Python checks the type of first argument and causes the appropriate registered function. However, he uses the default @singledispatch Function, if there is no specific service module.
6. itertools.groupby
You can group more elements that divide the same property with groupby Function with iTools.
Consider this example:
from itertools import groupby
transactions = [
{'type': 'credit', 'amount': 100},
{'type': 'credit', 'amount': 50},
{'type': 'debit', 'amount': 75},
{'type': 'debit', 'amount': 25}
]
# Group by transaction type
for trans_type, group in groupby(transactions, key=lambda x: x['type']):
total = sum(item['amount'] for item in group)
print(f"{trans_type}: ${total}")
How it works: groupby Groups subsequent elements with the same key. Returns couples (key, group_iterator). Critical: only groups neighboring elements, so if necessary sort your data.
7. functools.reduce
You can exploit reduce Funcools module function to apply a function to all elements in one value that can be obtained.
Take the following example:
from functools import reduce
# Calculate compound interest
monthly_rates = [1.01, 1.02, 0.99, 1.015] # Monthly growth rates
final_amount = reduce(lambda total, rate: total * rate, monthly_rates, 1000)
print(f"Final amount: ${final_amount:.2f}")
How it works: reduce It covers the function and uses it step by step: first to the initial value (1000) and the first rate, and then to this result and the second rate and so on. Works well for state -building operations.
Wrapping
To sum up, we saw how you can exploit:
@lru_cacheWhen you have functions that are often called the same argumentsitertools.chainWhen you need to process many data sources as one continuous streamfunctools.partialTo create specialized versions of general functionsitertools.combinationsfor systematic exploration of possibilities@singledispatchWhen you need to keep functions based on typesgroupbyfor capable further grouping operationsreducefor elaborate aggregations that build a state
The next time you write rushing loops or repetitive code, stop and think about whether one of them can be a more elegant solution.
It’s just a handful of tools that I consider helpful. There is a lot more if you look closer to the Python Standard library. So yes, elated discovery!
Bala Priya C He is a programmer and technical writer from India. He likes to work at the intersection of mathematics, programming, data science and content creation. Its interest areas and specialist knowledge include Devops, Data Science and Natural Language Processing. He likes to read, write, cod and coffee! He is currently working on learning and sharing his knowledge of programmers, creating tutorials, guides, opinions and many others. Bal also creates a coding resource and tutorial review.
