1. Python高阶函数:从入门到实战
在Python编程中,高阶函数(Higher-order function)是函数式编程范式的核心概念之一。简单来说,高阶函数就是能够接收其他函数作为参数,或者将函数作为返回值的函数。这种特性让Python代码可以更加简洁、优雅,也更容易实现复杂的逻辑抽象。
我第一次真正体会到高阶函数的威力是在处理一个数据分析项目时。当时需要清洗大量结构不一致的数据,传统的过程式编程让我写了大量重复的条件判断。直到同事建议使用map()和filter()等高阶函数,代码量直接减少了60%,而且逻辑变得更加清晰可读。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. Python内置高阶函数详解
2.1 map()函数:批量数据转换利器
map()函数的基本语法是:
python复制map(function, iterable, ...)
它会对可迭代对象中的每个元素应用指定的函数,返回一个map对象(迭代器)。例如,我们有一个数字列表需要计算平方:
python复制numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # 输出:[1, 4, 9, 16, 25]
注意:map()返回的是迭代器而不是列表,如果需要列表记得用list()转换
实际项目中,map()经常用于数据预处理。比如从数据库读取的字符串日期需要转换为datetime对象:
python复制from datetime import datetime
date_strings = ['2023-01-15', '2023-02-20', '2023-03-25']
dates = map(lambda s: datetime.strptime(s, '%Y-%m-%d'), date_strings)
2.2 filter()函数:优雅的数据筛选
filter()函数的语法与map()类似:
python复制filter(function, iterable)
它会对可迭代对象中的每个元素应用判断函数,保留返回True的元素。例如筛选出偶数:
python复制numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # 输出:[2, 4, 6, 8, 10]
在数据处理中,filter()可以替代很多for循环+if判断的场景。比如从日志中筛选出错误信息:
python复制logs = [
{'level': 'INFO', 'msg': 'System started'},
{'level': 'ERROR', 'msg': 'Disk full'},
{'level': 'WARNING', 'msg': 'Memory low'},
{'level': 'ERROR', 'msg': 'Network timeout'}
]
errors = filter(lambda log: log['level'] == 'ERROR', logs)
2.3 reduce()函数:累积计算神器
reduce()需要从functools模块导入:
python复制from functools import reduce
它的语法是:
python复制reduce(function, iterable[, initializer])
reduce()会对序列中的元素进行累积计算。最经典的例子是计算阶乘:
python复制from functools import reduce
def multiply(x, y):
return x * y
factorial_5 = reduce(multiply, range(1, 6)) # 1*2*3*4*5
print(factorial_5) # 输出:120
在金融计算中,reduce()可以方便地计算复合增长率:
python复制growth_rates = [0.05, 0.03, 0.07, 0.02] # 各期增长率
total_growth = reduce(lambda x, y: x * (1 + y), growth_rates, 1)
print(total_growth) # 输出:1.1835,即总增长18.35%
2.4 sorted()函数:灵活的自定义排序
sorted()的高阶特性体现在它的key参数上,可以接收一个函数来自定义排序规则:
python复制students = [
{'name': 'Alice', 'score': 90},
{'name': 'Bob', 'score': 85},
{'name': 'Charlie', 'score': 95}
]
# 按分数降序排序
sorted_students = sorted(students, key=lambda x: x['score'], reverse=True)
更复杂的场景中,key函数可以实现多条件排序。比如先按分数降序,分数相同再按姓名升序:
python复制sorted_students = sorted(
students,
key=lambda x: (-x['score'], x['name'])
)
3. 自定义高阶函数开发
3.1 函数作为参数
高阶函数最直接的用法就是接收函数作为参数。比如我们实现一个计时器装饰器:
python复制import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} executed in {end - start:.4f} seconds")
return result
return wrapper
@timer
def calculate_sum(n):
return sum(range(n))
calculate_sum(1000000)
# 输出:calculate_sum executed in 0.0342 seconds
3.2 函数作为返回值
高阶函数也可以返回函数。这种技术常用于创建特定功能的函数工厂:
python复制def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 输出:10
print(triple(5)) # 输出:15
3.3 闭包与高阶函数
闭包(Closure)是高阶函数的重要特性,它允许内部函数访问外部函数的变量:
python复制def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
print(c()) # 1
print(c()) # 2
print(c()) # 3
这种模式在状态保持的场景中非常有用,比如实现一个简单的缓存系统:
python复制def make_cache():
cache = {}
def cached_func(func):
def wrapper(*args):
if args in cache:
print("Returning cached result")
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
return cached_func
cache_decorator = make_cache()
@cache_decorator
def expensive_computation(x):
print("Computing...")
return x * x
print(expensive_computation(4)) # 计算并缓存
print(expensive_computation(4)) # 直接返回缓存结果
4. 高阶函数在实际项目中的应用
4.1 数据处理管道
高阶函数可以构建清晰的数据处理管道。假设我们需要处理电商订单数据:
python复制orders = [
{'id': 1, 'amount': 100, 'status': 'completed'},
{'id': 2, 'amount': 200, 'status': 'pending'},
{'id': 3, 'amount': 50, 'status': 'completed'},
{'id': 4, 'amount': 300, 'status': 'cancelled'}
]
# 数据处理步骤
def filter_completed(order):
return order['status'] == 'completed'
def calculate_tax(order):
order['tax'] = order['amount'] * 0.1
return order
def format_output(order):
return f"Order {order['id']}: ${order['amount']} (tax: ${order['tax']})"
# 构建处理管道
processed_orders = map(
format_output,
map(
calculate_tax,
filter(filter_completed, orders)
)
)
for order in processed_orders:
print(order)
4.2 策略模式实现
高阶函数可以优雅地实现策略模式,避免大量的条件判断:
python复制def linear_discount(price):
return price * 0.9 # 10%折扣
def threshold_discount(price):
return price - 50 if price > 200 else price
def seasonal_discount(price):
return price * 0.8 # 20%折扣
def calculate_total(prices, discount_strategy):
subtotal = sum(prices)
return discount_strategy(subtotal)
prices = [100, 50, 75]
print(calculate_total(prices, linear_discount)) # 202.5
print(calculate_total(prices, threshold_discount)) # 225
4.3 中间件架构
高阶函数是Web框架中间件的基础。我们可以模拟一个简单的中间件系统:
python复制def apply_middlewares(middlewares, handler):
def wrapped(request):
for middleware in reversed(middlewares):
handler = middleware(handler)
return handler(request)
return wrapped
def log_middleware(next_handler):
def wrapper(request):
print(f"Request received: {request}")
response = next_handler(request)
print(f"Response sent: {response}")
return response
return wrapper
def auth_middleware(next_handler):
def wrapper(request):
if 'token' not in request:
return {'error': 'Unauthorized'}, 401
return next_handler(request)
return wrapper
def hello_handler(request):
return {'message': f"Hello, {request.get('name', 'Guest')}"}
middlewares = [log_middleware, auth_middleware]
app = apply_middlewares(middlewares, hello_handler)
print(app({'token': 'abc123', 'name': 'Alice'}))
print(app({'name': 'Bob'})) # 返回未授权错误
5. 高阶函数性能优化与注意事项
5.1 惰性求值与生成器
高阶函数结合生成器可以实现惰性求值,节省内存:
python复制def big_data_processor(data):
for item in data:
# 模拟耗时处理
processed = expensive_operation(item)
yield processed
# 使用生成器表达式替代列表推导式
results = (x**2 for x in range(1000000))
# 链式处理
pipeline = map(
lambda x: x + 10,
filter(
lambda x: x % 3 == 0,
results
)
)
5.2 避免不必要的lambda
虽然lambda很方便,但有时预定义函数更清晰:
python复制# 不太好的写法
sorted_users = sorted(users, key=lambda u: (u.last_name, u.first_name))
# 更好的写法
def get_user_sort_key(user):
return (user.last_name, user.first_name)
sorted_users = sorted(users, key=get_user_sort_key)
5.3 函数组合技巧
使用functools模块的partial和reduce可以实现函数组合:
python复制from functools import partial, reduce
def compose(*functions):
return reduce(
lambda f, g: lambda x: f(g(x)),
functions,
lambda x: x
)
add_5 = lambda x: x + 5
multiply_3 = lambda x: x * 3
square = lambda x: x ** 2
transform = compose(add_5, multiply_3, square)
print(transform(2)) # (2^2)*3+5 = 17
5.4 类型提示与高阶函数
Python 3.5+的类型提示对高阶函数特别有用:
python复制from typing import Callable, TypeVar, Iterable
T = TypeVar('T')
R = TypeVar('R')
def my_map(func: Callable[[T], R], iterable: Iterable[T]) -> Iterable[R]:
return (func(x) for x in iterable)
numbers: list[int] = [1, 2, 3]
squared: list[int] = list(my_map(lambda x: x**2, numbers))
6. 高阶函数与其他Python特性的结合
6.1 装饰器的高级用法
装饰器本身就是高阶函数的应用,可以实现很多强大功能:
python复制def retry(max_attempts=3, delay=1):
def decorator(func):
import time
from functools import wraps
@wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
if attempts == max_attempts:
raise
time.sleep(delay)
return wrapper
return decorator
@retry(max_attempts=5, delay=2)
def unreliable_api_call():
import random
if random.random() < 0.7:
raise ValueError("API failed")
return "Success"
6.2 类方法与高阶函数
类方法也可以作为高阶函数使用:
python复制class DataProcessor:
def __init__(self, data):
self.data = data
def apply_transforms(self, *transforms):
result = self.data
for transform in transforms:
result = transform(result)
return result
processor = DataProcessor([1, 2, 3, 4, 5])
result = processor.apply_transforms(
lambda x: filter(lambda n: n % 2 == 0, x),
lambda x: map(lambda n: n * 2, x),
list
)
print(result) # [4, 8]
6.3 异步高阶函数
高阶函数也可以用于异步编程:
python复制import asyncio
async def async_map(func, iterable):
return [await func(item) for item in iterable]
async def process_data(data):
async def transform(item):
await asyncio.sleep(0.1) # 模拟IO操作
return item * 2
return await async_map(transform, data)
async def main():
data = [1, 2, 3, 4, 5]
result = await process_data(data)
print(result) # [2, 4, 6, 8, 10]
asyncio.run(main())
7. 高阶函数的最佳实践与常见误区
7.1 何时使用高阶函数
适合使用高阶函数的场景:
- 需要对一组数据应用相同的操作
- 需要实现回调机制
- 需要构建处理管道或中间件
- 需要实现策略模式或模板方法
不适合的场景:
- 简单的一次性操作
- 性能极其敏感的代码段
- 逻辑特别复杂需要大量注释才能理解的情况
7.2 可读性与维护性
提高高阶函数可读性的技巧:
- 为关键函数和lambda添加类型提示
- 给复杂的转换操作命名而不是直接写lambda
- 保持函数链不要太长(一般不超过3-4个)
- 适当添加注释解释复杂的函数组合
7.3 性能考量
高阶函数的性能特点:
- map/filter通常比等价的for循环稍快
- 但lambda函数会比预定义的函数稍慢
- 过长的函数调用链会增加调用开销
优化建议:
- 对性能关键路径进行profile测试
- 考虑使用列表推导式替代简单的map/filter
- 对于大数据集,考虑使用生成器表达式
7.4 测试高阶函数
测试高阶函数的一些策略:
python复制import unittest
def test_map_function():
def square(x):
return x * x
test_cases = [
([1, 2, 3], [1, 4, 9]),
([], []),
([-1, 0, 1], [1, 0, 1])
]
for input_data, expected in test_cases:
result = list(map(square, input_data))
assert result == expected, f"Failed for {input_data}"
class TestHigherOrderFunctions(unittest.TestCase):
def test_filter(self):
is_even = lambda x: x % 2 == 0
self.assertEqual(list(filter(is_even, [1, 2, 3, 4])), [2, 4])
def test_custom_hof(self):
def apply_twice(f, x):
return f(f(x))
add_one = lambda x: x + 1
self.assertEqual(apply_twice(add_one, 5), 7)
8. 高阶函数在Python生态中的应用实例
8.1 Django中的高阶函数应用
Django框架大量使用高阶函数概念。例如视图装饰器:
python复制from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
@login_required
def my_view(request):
# 只有登录用户通过GET或POST方法才能访问
return HttpResponse("Hello")
8.2 Pandas中的apply方法
Pandas的apply系列方法是高阶函数的典型应用:
python复制import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
# 对每列应用函数
result = df.apply(lambda col: col.max() - col.min(), axis=0)
# 对每行应用函数
df['sum'] = df.apply(lambda row: row['A'] + row['B'], axis=1)
8.3 Flask的路由系统
Flask的路由系统也是基于高阶函数:
python复制from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome"
@app.route('/user/<username>')
def show_user(username):
return f"User {username}"
# 等价于高阶函数调用
# index = app.route('/')(index)
# show_user = app.route('/user/<username>')(show_user)
8.4 pytest的fixture系统
pytest的fixture系统利用高阶函数实现依赖注入:
python复制import pytest
@pytest.fixture
def database_connection():
conn = create_connection()
yield conn
conn.close()
def test_query(database_connection):
result = database_connection.execute("SELECT 1")
assert result == 1
9. 高阶函数与设计模式
9.1 装饰器模式
装饰器模式是高阶函数的直接应用:
python复制def bold(func):
def wrapper(*args, **kwargs):
return f"<b>{func(*args, **kwargs)}</b>"
return wrapper
def italic(func):
def wrapper(*args, **kwargs):
return f"<i>{func(*args, **kwargs)}</i>"
return wrapper
@bold
@italic
def hello(name):
return f"Hello, {name}"
print(hello("Alice")) # <b><i>Hello, Alice</i></b>
9.2 策略模式
高阶函数简化了策略模式的实现:
python复制def linear_search(items, key):
for item in items:
if item == key:
return True
return False
def binary_search(sorted_items, key):
# 实现二分查找
pass
def search_factory(algorithm='linear'):
strategies = {
'linear': linear_search,
'binary': binary_search
}
return strategies[algorithm]
searcher = search_factory('binary')
result = searcher([1, 2, 3, 4, 5], 3)
9.3 模板方法模式
高阶函数可以实现模板方法:
python复制def template_method(custom_step):
def wrapper():
print("执行前置操作")
result = custom_step()
print("执行后置操作")
return result
return wrapper
@template_method
def my_algorithm():
print("执行自定义步骤")
return 42
result = my_algorithm()
9.4 观察者模式
高阶函数可以简化观察者模式的实现:
python复制def create_observable():
observers = []
def register(observer):
observers.append(observer)
def notify(*args, **kwargs):
for observer in observers:
observer(*args, **kwargs)
return register, notify
register, notify = create_observable()
register(lambda x: print(f"Observer 1: {x}"))
register(lambda x: print(f"Observer 2: {x}"))
notify("Something happened!")
10. 高阶函数进阶技巧
10.1 柯里化(Currying)
柯里化是把多参数函数转换为一系列单参数函数的技术:
python复制def curry(func):
from functools import partial
def wrapper(*args):
if len(args) >= func.__code__.co_argcount:
return func(*args)
return partial(wrapper, *args)
return wrapper
@curry
def add_three_numbers(a, b, c):
return a + b + c
add_5 = add_three_numbers(5)
add_5_and_10 = add_5(10)
result = add_5_and_10(15) # 30
10.2 函数记忆化(Memoization)
高阶函数可以实现记忆化缓存:
python复制def memoize(func):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
wrapper.cache = cache
return wrapper
@memoize
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(50)) # 计算大数时明显更快
10.3 惰性求值
高阶函数可以实现惰性求值:
python复制class Lazy:
def __init__(self, func):
self.func = func
self._value = None
def __call__(self):
if self._value is None:
self._value = self.func()
return self._value
@Lazy
def expensive_computation():
print("Performing expensive computation...")
return 42
# 只有在第一次调用时才会计算
print(expensive_computation())
print(expensive_computation()) # 直接返回缓存值
10.4 函数组合
高阶函数可以实现数学上的函数组合:
python复制def compose(*functions):
from functools import reduce
def apply(f, g):
return lambda x: f(g(x))
return reduce(apply, functions, lambda x: x)
add_5 = lambda x: x + 5
multiply_3 = lambda x: x * 3
square = lambda x: x ** 2
transform = compose(add_5, multiply_3, square)
print(transform(2)) # (2^2)*3+5 = 17
11. 高阶函数调试技巧
11.1 调试装饰器
可以创建专门的调试装饰器:
python复制def debug(func):
import inspect
from functools import wraps
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned: {result}")
return result
return wrapper
@debug
def add(a, b):
return a + b
add(3, 5)
11.2 跟踪函数调用
高阶函数可以帮助跟踪调用链:
python复制def trace(func):
depth = 0
def wrapper(*args, **kwargs):
nonlocal depth
prefix = " " * depth
print(f"{prefix}-> {func.__name__}({args}, {kwargs})")
depth += 1
result = func(*args, **kwargs)
depth -= 1
print(f"{prefix}<- {func.__name__} => {result}")
return result
return wrapper
@trace
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
factorial(4)
11.3 性能分析装饰器
高阶函数可以集成性能分析:
python复制import time
from functools import wraps
def profile(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} executed in {end - start:.6f} seconds")
return result
return wrapper
@profile
def process_data(data):
time.sleep(0.5) # 模拟耗时操作
return sum(data)
process_data(range(1000))
12. 高阶函数与并发编程
12.1 多线程与高阶函数
高阶函数可以简化线程池的使用:
python复制from concurrent.futures import ThreadPoolExecutor
def parallel_map(func, iterable, max_workers=4):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
return list(executor.map(func, iterable))
results = parallel_map(lambda x: x**2, range(10))
print(results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
12.2 多进程与高阶函数
类似地,可以应用于多进程:
python复制from concurrent.futures import ProcessPoolExecutor
def cpu_intensive(x):
return x * x # 模拟CPU密集型计算
def parallel_process(func, iterable, max_workers=None):
with ProcessPoolExecutor(max_workers=max_workers) as executor:
return list(executor.map(func, iterable))
numbers = list(range(1, 1001))
results = parallel_process(cpu_intensive, numbers)
12.3 异步IO与高阶函数
高阶函数也可以用于异步编程:
python复制import asyncio
async def async_map(func, iterable):
return await asyncio.gather(*[func(item) for item in iterable])
async def process_item(item):
await asyncio.sleep(0.1) # 模拟IO操作
return item * 2
async def main():
data = range(5)
results = await async_map(process_item, data)
print(results) # [0, 2, 4, 6, 8]
asyncio.run(main())
13. 高阶函数与元编程
13.1 动态函数生成
高阶函数可以实现动态函数生成:
python复制def make_arithmetic_function(operation):
if operation == 'add':
return lambda a, b: a + b
elif operation == 'subtract':
return lambda a, b: a - b
elif operation == 'multiply':
return lambda a, b: a * b
elif operation == 'divide':
return lambda a, b: a / b
else:
raise ValueError("Unknown operation")
adder = make_arithmetic_function('add')
print(adder(3, 5)) # 8
13.2 函数注册表
高阶函数可以实现插件系统:
python复制class FunctionRegistry:
def __init__(self):
self._functions = {}
def register(self, name):
def decorator(func):
self._functions[name] = func
return func
return decorator
def get(self, name):
return self._functions.get(name)
registry = FunctionRegistry()
@registry.register('greet')
def greet(name):
return f"Hello, {name}!"
@registry.register('farewell')
def farewell(name):
return f"Goodbye, {name}!"
print(registry.get('greet')('Alice'))
print(registry.get('farewell')('Bob'))
13.3 函数组合的元编程
高阶函数可以实现更高级的函数组合:
python复制def pipeline(*functions):
from functools import reduce
def compose(f, g):
return lambda x: f(g(x))
return reduce(compose, functions, lambda x: x)
def double(x):
return x * 2
def increment(x):
return x + 1
def square(x):
return x ** 2
transform = pipeline(double, increment, square)
print(transform(3)) # ((3*2)+1)^2 = 49
14. 高阶函数与类型系统
14.1 类型注解与高阶函数
Python的类型提示对高阶函数特别有用:
python复制from typing import Callable, TypeVar, List
T = TypeVar('T')
R = TypeVar('R')
def apply_to_all(func: Callable[[T], R], items: List[T]) -> List[R]:
return [func(item) for item in items]
numbers: List[int] = [1, 2, 3, 4]
squared: List[int] = apply_to_all(lambda x: x**2, numbers)
14.2 泛型高阶函数
可以定义更通用的高阶函数:
python复制from typing import Callable, TypeVar, Iterable, Any
T = TypeVar('T')
U = TypeVar('U')
V = TypeVar('V')
def zip_with(
func: Callable[[T, U], V],
iter1: Iterable[T],
iter2: Iterable[U]
) -> Iterable[V]:
return (func(x, y) for x, y in zip(iter1, iter2))
result = list(zip_with(
lambda a, b: a + b,
[1, 2, 3],
[10, 20, 30]
))
print(result) # [11, 22, 33]
14.3 高阶函数与mypy
使用mypy检查高阶函数的类型安全:
python复制# 示例代码,实际需要安装mypy并运行检查
from typing import Callable
def apply_func(func: Callable[[int], str], value: int) -> str:
return func(value)
# mypy会检查类型是否匹配
result = apply_func(lambda x: f"Number: {x}", 42) # 正确
# result = apply_func(lambda x: x * 2, 42) # mypy会报错
15. 高阶函数与函数式编程库
15.1 使用toolz库
toolz库提供了更多高阶函数工具:
python复制from toolz import compose, pipe
def add_one(x):
return x + 1
def square(x):
return x * x
# 组合函数
transform = compose(str, square, add_one)
print(transform(3)) # "16"
# 管道操作
result = pipe(3, add_one, square, str)
print(result) # "16"
15.2 使用fn.py库
fn.py提供了更多函数式编程特性:
python复制from fn import F, _
# 函数组合
func = (F() >> (lambda x: x + 1) >> (lambda x: x * 2))
print(func(3)) # 8
# 偏函数应用
add = _ + _
print(add(3, 5)) # 8
15.3 使用cytoolz提高性能
cytoolz是toolz的Cython实现,性能更高:
python复制from cytoolz import compose, take
def double(x):
return x * 2
def increment(x):
return x + 1
transform = compose(double, increment)
print(transform(5)) # 12
# 惰性求值
squares = (x*x for x in range(1000000))
first_5 = take(5, squares)
print(list(first_5)) # [0, 1, 4, 9, 16]
16. 高阶函数与并发模式
16.1 并行处理模式
高阶函数可以简化并行处理:
python复制from multiprocessing import Pool
def parallel_apply(func, data, processes=None):
with Pool(processes=processes) as pool:
return pool.map(func, data)
def process_item(x):
return x * x
data = range(10)
results = parallel_apply(process_item, data)
print(results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
16.2 异步批处理
高阶函数可以实现异步批处理:
python复制import asyncio
async def batch_process(func, items, batch_size=10):
results = []
for i in range(0, len(items), batch_size):
batch = items[i:i + batch_size]
batch_results = await asyncio.gather(*[func(item) for item in batch])
results.extend(batch_results)
return results
async def process_item(item):
await asyncio.sleep(0.1) # 模拟IO操作
return item * 2
async def main():
data = range(20)
results = await batch_process(process_item, data, batch_size=5)
print(results)
asyncio.run(main())
16.3 流水线处理模式
高阶函数可以实现并发流水线:
python复制from concurrent.futures import ThreadPoolExecutor
import queue
def pipeline(stages, input_queue, output_queue):
def worker(input_q, output_q, func):
while True:
item = input_q.get()
if item is None: # 哨兵值,表示结束
output_q.put(None)
break
result = func(item)
output_q.put(result)
queues = [input_queue] + [queue.Queue() for _ in range(len(stages)-1)] + [output_queue]
with ThreadPoolExecutor(max_workers=len(stages)) as executor:
futures = [
executor.submit(worker, queues[i], queues[i+1], stage)
for i, stage in enumerate(stages)
]
# 等待所有工作完成
for f in futures:
f.result()
# 使用示例
input_q = queue.Queue()
output_q = queue.Queue()
stages = [
lambda x: x + 1, # 阶段1:加1
lambda x: x * 2, # 阶段2:乘2
lambda x: f"Result: {x}" # 阶段3:格式化
]
# 启动流水线
pipeline(stages, input_q, output_q)
# 输入数据
for i in range(5):
input_q.put(i)
# 结束信号
input_q.put(None)
# 获取结果
while True:
result = output_q.get()
if result is None:
break
print(result)
17. 高阶函数与测试
17.1 模拟高阶函数
测试中使用高阶函数的技巧:
python复制from unittest.mock import Mock, MagicMock
def test_higher_order_function():
# 创建一个模拟函数
mock_func = Mock(return_value=42)
# 创建一个接收函数作为参数的高阶函数
def higher_order(func, x):
return func(x) * 2
# 测试高阶函数
result = higher_order(mock_func, 10)
# 验证
assert result == 84
mock_func.assert_called_once_with(10)
17.2 参数化测试
高阶函数可以简化参数化测试:
python复制import pytest
def add(a, b):
return a + b
test_data = [
(1, 1, 2),
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0)
]
@p
