Detailed explanation of itertools, functools, and operator function modules in python

itertools module

In interface automation work, we often need to process large amounts of data and perform various iterative operations. To improve efficiency and simplify code, Python provides the itertools module, which contains functions for creating efficient loop iterators. Next, let us understand and use the itertools module together, giving five sample codes in actual interface automation work.

Example 1: Iterator continuous counting

In interface testing, sometimes we need to generate a series of consecutive numbers. The itertools.count() function can help us create an infinite iterator that generates an increasing integer with each iteration. Here is a sample code:

import itertools
for num in itertools.count(start=1, step=1):
    print(num)
    if num == 10:
        break

In the above code, we use the count() function to create an iterator starting from 1 with a step size of 1, and print out the first 10 numbers through the loop.

Example 2: Iterator loop repeats

Sometimes we need to repeat the contents of a sequence or iterator. The itertools.cycle() function can help us create an infinite loop iterator that repeats the elements in the sequence each iteration. Here is a sample code:

import itertools
seq = [1, 2, 3]
for num in itertools.cycle(seq):
    print(num)
    if num == 3:
        break

In the above code, we use the cycle() function to create an infinite loop iterator that repeats the elements in the sequence seq on each iteration until it iterates to the number 3.

Example 3: Iterator combination arrangement

Sometimes we need to combine or permute sequences to generate all possible combinations or permutations. The itertools.combinations() and itertools.permutations() functions can help us achieve this goal. Here is a sample code:

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)

In the above code, we use the combinations() function to generate all combinations of length 2 in the sequence seq, and use the permutations() function to generate all permutations of length 2 in the sequence seq.

Example 4: Iterator conditional slicing

Sometimes we need to slice a sequence based on conditions and only retain elements that meet the conditions. The itertools.takewhile() function can help us achieve this goal. Here is a sample code:

import itertools
seq = [1, 2, 3, 4, 5, 6]
# 保留小于等于3的元素
result = list(itertools.takewhile(lambda x: x <= 3, seq))
print(result)

In the above code, we use the takewhile() function to retain elements less than or equal to 3 in the sequence seq, and store the results in a list.

Example 5: Iterator filters by condition

Sometimes we need to filter elements that meet the conditions from the sequence based on conditions. The itertools.filterfalse() function can help us achieve this purpose. Here is a sample code:

import itertools

seq = [1, 2, 3, 4, 5, 6]

# Filter out non-even elements

result = list(itertools.filterfalse(lambda x: x % 2 == 0, seq))

print(result)

In the above code, we use the filterfalse() function to filter out non-even elements from the sequence seq and store the results in a list.

functools module

In actual interface automation work, we often need to deal with functions and callable objects, and Python's functools module provides some convenient functions and tools for the operation of high-order functions and callable objects. Next, let us understand and use the functools module together, giving five example codes in actual interface automation work.

Example 1: Partial function

In interface automation work, sometimes we need to create a new function, which is a fixed version of some parameters of the original function. The partial() function of the functools module can help us achieve this goal. Here is a sample code:

import functools
# 原始函数
def add(a, b):
    return a + b
# 创建一个固定了第一个参数的新函数
add_5 = functools.partial(add, 5)
# 调用新函数
result = add_5(10)
print(result)

In the above code, we use the partial() function to create a new function add_5, which is a fixed-argument version of the original function add(). We fixed the first parameter to 5 and made it the default parameter for the new function, which can then be used for calculations.

Example 2: Function caching

In interface automation work, some functions may be called frequently, and the calculation results of these functions are the same. In order to improve efficiency, we can use the lru_cache() function of the functools module to cache the function to avoid repeated calculations. Here is a sample code:

import functools
# 需要进行缓存的函数
@functools.lru_cache()
def get_data(url):
    # 发送HTTP请求并获取数据
    # ...
    return data
# 第一次调用函数,会执行实际的计算
result1 = get_data("http://example.com")
# 第二次调用函数,会直接返回缓存的结果
result2 = get_data("http://example.com")

In the above code, we use the lru_cache() function to cache the get_data() function. When the function is called for the first time, the actual calculation is performed and the results are cached, and subsequent calls directly return the cached results, thus improving the execution efficiency of the function.

Example 3: Function decorator

During interface automation work, we may need to perform additional operations or add functionality to some functions. The wraps() function of the functools module can help us create function decorators to wrap functions without modifying the original function code. Here is a sample code:

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)

In the above code, we define a decorator function log_decorator, which uses the wraps() function to retain the metadata of the decorated function, and then creates a new function wrapper to wrap the original function. In the wrapper function, we can add additional operations, such as printing logs. Finally, we apply the decorator to the function calculate using the @log_decorator syntax.

Example 4: Function Comparator

In interface automation work, we may need to sort a set of objects or find the maximum/minimum value. The cmp_to_key() function of the functools module can help us convert old-style comparison functions into key functions for use in sorting and search operations. Here is a sample code:

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)

In the above code, we define an old-style comparison function compare and then use the cmp_to_key() function to convert it into a key function key_func. By passing key functions to the sort(), max(), and min() functions, we can use old-style comparison functions in sorting and search operations.

Example 5: Function retry

In interface automation work, sometimes we need to retry certain functions to handle possible failure situations. The retry() function of the functools module can help us implement the retry logic of the function. Here is a sample code:

import functools
# 需要重试的函数
@functools.retry()
def send_request(url):
    # 发送HTTP请求
    # ...
    # 如果请求失败,抛出异常
    raise Exception("Request failed")
# 调用带重试逻辑的函数
try:
    send_request("http://example.com")
except Exception as e:
    print("Error:", str(e))

In the above code, we use the retry() function to wrap the retry logic of the send_request() function. If the function throws an exception, the retry() function will automatically retry until the specified number of retries is reached. This way we can handle possible failure situations of function calls.

operator module

When people are programming in Python, they often use various operators to perform numerical calculations, logical judgments and other operations. However, sometimes we need to process these operators in the form of functions so that they can be applied more flexibly in different scenarios. At this time, Python's operator module comes in handy. The operator module provides a series of functions to replace common operators, allowing us to perform operations in a functional manner. This article will introduce the use of the operator module and provide five sample codes for actual interface automation work.

Example 1: Comparison operators

In interface automation work, we often need to compare the size or equality of two values. Comparison operations can be easily performed using the functions of the operator module. Here is a sample code:

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)  # 输出False
print(result2)  # 输出False
print(result3)  # 输出True

In the above code, we use the lt(), eq() and gt() functions to compare the size relationship between variables a and b. By using the functions of the operator module, we can express comparison operations clearly.

Example 2: Arithmetic operators

In interface automation work, we sometimes need to perform arithmetic operations on numbers, such as addition, subtraction, multiplication, etc. The operator module provides a series of functions to replace these arithmetic operators. Here is a sample code:

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)  # 输出15
print(result2)  # 输出5
print(result3)  # 输出50

In the above code, we use add(), sub() and mul() functions to perform addition, subtraction and multiplication operations. By using the functions of the operator module, we can avoid using operators directly, making the code clearer and easier to understand.

Example 3: Logical operators

In interface automation work, we often need to perform logical operations, such as AND, OR, NOT, etc. The operator module provides corresponding functions to perform logical operations. Here is a sample code:

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)  # 输出False
print(result2)  # 输出True
print(result3)  # 输出False

In the above code, we use the and_(), or_() and not_() functions to perform logical operations of AND, OR and NOT. By using the functions of the operator module, we can handle logical operations more flexibly.

Example 4: Sequence Operator

In interface automation work, we may need to perform some operations on sequences (such as lists and tuples), such as splicing, repeating, etc. The operator module provides corresponding functions to perform sequence operations. Here is a sample code:

import operator

sheet1 = [1, 2, 3]

list2 = [4, 5, 6]

# Use functions for sequence operations

result1 = operator.concat(list1, list2)  # list1 + list2

result2 = operator.mul(list1, 3)  # list1 * 3

print(result1) # Output [1, 2, 3, 4, 5, 6]

print(result2) # Output [1, 2, 3, 1, 2, 3, 1, 2, 3]

In the above code, we use the concat() function to concatenate lists, and the mul() function to perform repeated operations on lists. By using the functions of the operator module, we can operate on the sequence more conveniently.

Example 5: Indexing and slicing operators

In interface automation work, we often need to perform indexing and slicing operations on lists, strings, etc. The operator module provides corresponding functions for indexing and slicing operations. Here is a sample code:

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)  # 输出3
print(result2)  # 输出None
print(result3)  # 输出None
print(list1)  # 输出[1, 10, 3, 5]

In the above code, we use the getitem() function to get the specified index element of the list, use the setitem() function to set the specified index element of the list, and use the delitem() function to delete the specified index element of the list. By using the functions of the operator module, we can perform indexing and slicing operations more conveniently.

Finally: The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves [guaranteed 100% free]

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

Guess you like

Origin blog.csdn.net/wx17343624830/article/details/132975705