Python上下文管理器如何感知其上下文内的代码逻辑?
Python上下文管理器进阶:无显式传递实现上下文感知逻辑
我平时常用Python的上下文管理器替代try-catch-finally逻辑,最近发现了一种进阶用法:上下文管理器不需要显式传递给方法,就能感知其上下文内的代码执行。比如以下几种库中的模式:
通用示例模式
first = SomeClass() second = SomeOtherClass() with SomeContext() as c: first.do_calculation() second.do_calculation() c.execute()
Prefect工作流引擎的Flow上下文
Flow上下文能自动感知内部的task:
from prefect import task, Flow @task def first(x, y): return x + y @task def second(x, y): return x*y with Flow('test-flow') as flow: res_first = first(1, 2) res_second = second(res_first) flow.run()
gs-quant的PricingContext逻辑
在上下文内调用.price()方法时,上下文能影响计算逻辑,还能通过批量请求减少开销:
ir_swap = InterestRateSwap(...) # 为简化使用虚构类名 eq_option = EquityOption(...) with PricingContext(...) as p: ir_price = ir_swap.price() eq_price = eq_option.price() print(ir_price.result(), eq_price.result())
我的需求
我想实现如下逻辑,让MyContext无需显式传入,就能影响MyClass的calculate方法:
class MyClass: def __init__(self): ... def calculate(self): ... my_class = MyClass() with MyContext() as c: my_class.calculate()
我知道可以直接传递上下文参数,但上述库都没有采用这种方式,推测是用了全局默认管理器,但不清楚具体的良好设计方案,而且相关库的源码复杂,难以解析。
内容的提问来源于stack exchange,提问作者OJK
相关产品推荐
相关产品推荐

