Practical Use of Python itertools, functools, and operator Modules for Interface Automation
This article introduces Python’s itertools, functools, and operator modules and demonstrates five practical code examples for each, showing how to simplify data iteration, function handling, and operator usage in interface automation tasks.
In interface automation, Python’s standard library modules itertools , functools , and operator provide powerful tools for efficient iteration, function manipulation, and functional operators.
itertools module – five examples
Example 1: Continuous counting
Creates an infinite counter and prints the first ten numbers.
import itertools
for num in itertools.count(start=1, step=1):
print(num)
if num == 10:
breakExample 2: Repeating a sequence
Repeats a given sequence indefinitely until a condition is met.
import itertools
seq = [1, 2, 3]
for num in itertools.cycle(seq):
print(num)
if num == 3:
breakExample 3: Combinations and permutations
Generates all 2‑element combinations and permutations of a list.
import itertools
seq = [1, 2, 3]
for combination in itertools.combinations(seq, r=2):
print(combination)
for permutation in itertools.permutations(seq, r=2):
print(permutation)Example 4: Conditional slicing with takewhile
Collects elements from a sequence while a predicate holds.
import itertools
seq = [1, 2, 3, 4, 5, 6]
result = list(itertools.takewhile(lambda x: x <= 3, seq))
print(result)Example 5: Filtering with filterfalse
Filters out even numbers, keeping only odd ones.
import itertools
seq = [1, 2, 3, 4, 5, 6]
result = list(itertools.filterfalse(lambda x: x % 2 == 0, seq))
print(result)functools module – five examples
Example 1: Partial functions
Creates a new function with some arguments fixed.
import functools
def add(a, b):
return a + b
add_5 = functools.partial(add, 5)
result = add_5(10)
print(result)Example 2: Function caching with lru_cache
Caches results of a function to avoid repeated computation.
import functools
@functools.lru_cache()
def get_data(url):
# send HTTP request and retrieve data
# ...
return data
result1 = get_data("http://example.com")
result2 = get_data("http://example.com")Example 3: Creating decorators with wraps
Defines a logging decorator that preserves original metadata.
import functools
def log_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Calling function:", func.__name__)
result = func(*args, **kwargs)
print("Function", func.__name__, "finished")
return result
return wrapper
@log_decorator
def calculate(a, b):
return a + b
result = calculate(5, 10)
print(result)Example 4: Converting old‑style comparators with cmp_to_key
Turns a comparator function into a key function for sorting and searching.
import functools
def compare(a, b):
if a < b:
return -1
elif a > b:
return 1
else:
return 0
key_func = functools.cmp_to_key(compare)
data = [4, 2, 6, 1, 3]
data.sort(key=key_func)
print(data)
max_value = max(data, key=key_func)
min_value = min(data, key=key_func)
print("Max:", max_value)
print("Min:", min_value)Example 5: Retry logic (note: retry is illustrative)
Wraps a function so that it is automatically retried on failure.
import functools
@functools.retry()
def send_request(url):
# send HTTP request
# ...
raise Exception("Request failed")
try:
send_request("http://example.com")
except Exception as e:
print("Error:", str(e))operator module – five examples
Example 1: Comparison operators
import operator
a = 10
b = 5
result1 = operator.lt(a, b) # a < b
result2 = operator.eq(a, b) # a == b
result3 = operator.gt(a, b) # a > b
print(result1)
print(result2)
print(result3)Example 2: Arithmetic operators
import operator
a = 10
b = 5
result1 = operator.add(a, b) # a + b
result2 = operator.sub(a, b) # a - b
result3 = operator.mul(a, b) # a * b
print(result1)
print(result2)
print(result3)Example 3: Logical operators
import operator
a = True
b = False
result1 = operator.and_(a, b) # a and b
result2 = operator.or_(a, b) # a or b
result3 = operator.not_(a) # not a
print(result1)
print(result2)
print(result3)Example 4: Sequence operations
import operator
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result1 = operator.concat(list1, list2) # list1 + list2
result2 = operator.mul(list1, 3) # list1 * 3
print(result1)
print(result2)Example 5: Indexing and slicing operators
import operator
list1 = [1, 2, 3, 4, 5]
result1 = operator.getitem(list1, 2) # list1[2]
result2 = operator.setitem(list1, 1, 10) # list1[1] = 10
result3 = operator.delitem(list1, 3) # del list1[3]
print(result1)
print(result2)
print(result3)
print(list1)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.