```python
import asyncio
import time
from typing import Callable, Any
# 回调地狱版本
def callback_hell_example():
传统的回调地狱示例
def step1(callback: Callable):
print(步骤1开始)
time.sleep(1)
callback(步骤1结果)
def step2(data: str, callback: Callable):
print(f处理 {data})
time.sleep(1)
callback(步骤2结果)
def step3(data: str, callback: Callable):
print(f处理 {data})
time.sleep(1)
callback(步骤3结果)
def final_callback(result: str):
print(f最终结果: {result})
# 回调嵌套 - 这就是回调地狱
step1(lambda result1:
step2(result1, lambda result2:
step3(result2, final_callback)))
# 使用asyncio的回调改进版本
def asyncio_callback_example():
使用asyncio改进的回调版本
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
def step1():
print(步骤1开始)
future = loop.create_future()
loop.call_later(1, lambda: future.set_result(步骤1结果))
return future
def step2(data: str):
print(f处理 {data})
future = loop.create_future()
loop.call_later(1, lambda: future.set_result(步骤2结果))
return future
def step3(data: str):
print(f处理 {data})
future = loop.create_future()
loop.call_later(1, lambda: future.set_result(步骤3结果))
return future
# 使用future链式调用
step1().add_done_callback(
lambda f: step2(f.result()).add_done_callback(
lambda f: step3(f.result()).add_done_callback(
lambda f: print(f最终结果: {f.result()})
)
)
)
loop.run_until_complete(asyncio.sleep(4))
loop.close()
# async/await优雅版本
async def async_elegant_example():
使用async/await的优雅版本
async def step1() -> str:
print(步骤1开始)
await asyncio.sleep(1)
return 步骤1结果
async def step2(data: str) -> str:
print(f处理 {data})
await asyncio.sleep(1)
return 步骤2结果
async def step3(data: str) -> str:
print(f处理 {data})
await asyncio.sleep(1)
return 步骤3结果
# 使用await的线性代码,避免了回调嵌套
result1 = await step1()
result2 = await step2(result1)
final_result = await step3(result2)
print(f最终结果: {final_result})
# 并发执行的async/await版本
async def async_concurrent_example():
并发执行的async/await版本
async def fetch_data(source: str, delay: float) -> str:
print(f从 {source} 获取数据)
await asyncio.sleep(delay)
return f{source}的数据
async def process_data(data: str) -> str:
print(f处理 {data})
await asyncio.sleep(0.5)
return f已处理的{data}
# 并发执行多个任务
tasks = [
fetch_data(API1, 1.0),
fetch_data(API2, 1.5),
fetch_data(API3, 0.8)
]
# 等待所有任务完成
results = await asyncio.gather(tasks)
# 顺序处理结果
processed_results = []
for result in results:
processed = await process_data(result)
processed_results.append(processed)
print(f所有结果: {processed_results})
# 错误处理对比
def callback_error_handling():
回调方式的错误处理(复杂)
def step1(callback, error_callback):
try:
print(步骤1开始)
time.sleep(1)
callback(步骤1结果)
except Exception as e:
error_callback(e)
def step2(data: str, callback, error_callback):
try:
print(f处理 {data})
time.sleep(1)
if 错误 in data:
raise ValueError(步骤2出错)
callback(步骤2结果)
except Exception as e:
error_callback(e)
def handle_error(error: Exception):
print(f错误处理: {error})
# 复杂的错误处理回调嵌套
step1(
lambda result1: step2(
result1,
lambda result2: print(f成功: {result2}),
handle_error
),
handle_error
)
async def async_error_handling():
async/await的错误处理(简洁)
async def step1() -> str:
print(步骤1开始)
await asyncio.sleep(1)
return 步骤1结果
async def step2(data: str) -> str:
print(f处理 {data})
await asyncio.sleep(1)
if 错误 in data:
raise ValueError(步骤2出错)
return 步骤2结果
try:
result1 = await step1()
result2 = await step2(result1)
print(f成功: {result2})
except Exception as e:
print(f错误处理: {e})
# 性能对比示例
async def performance_comparison():
性能对比演示
async def async_io_operation(name: str, delay: float):
print(f{name} 开始)
await asyncio.sleep(delay)
print(f{name} 完成)
return f{name}结果
# 使用async/await可以轻松实现并发
start_time = time.time()
# 并发执行多个IO操作
results = await asyncio.gather(
async_io_operation(任务1, 1.0),
async_io_operation(任务2, 1.0),
async_io_operation(任务3, 1.0)
)
end_time = time.time()
print(f异步执行时间: {end_time - start_time:.2f}秒)
print(f结果: {results})
def main():
print(=== 回调地狱示例 ===)
callback_hell_example()
print( === asyncio回调改进 ===)
asyncio_callback_example()
print( === async/await优雅版本 ===)
asyncio.run(async_elegant_example())
print( === 并发执行示例 ===)
asyncio.run(async_concurrent_example())
print( === 错误处理对比 ===)
print(回调方式:)
callback_error_handling()
print(async/await方式:)
asyncio.run(async_error_handling())
print( === 性能对比 ===)
asyncio.run(performance_comparison())
if __name__ == __main__:
main()
```
这篇文章通过代码示例展示了Python异步编程从回调地狱到async/await的优雅进化:
回调地狱问题:
- 深度嵌套的回调函数
- 错误处理复杂
- 代码难以阅读和维护
- 控制流不直观
asyncio回调改进:
- 使用Future对象
- 链式回调稍微改善可读性
- 但仍然存在嵌套问题
async/await的革命:
- 线性代码结构,类似同步代码
- 内置错误处理机制
- 更好的可读性和可维护性
- 原生支持并发执行
- 性能优势明显
async/await语法让异步代码看起来像同步代码,大大降低了异步编程的认知负担,同时保持了非阻塞IO的高性能特性。这种演进使得Python异步编程更加优雅和实用。
1147

被折叠的 条评论
为什么被折叠?



