Python 中的依赖注入与引导脚本实践
1. 依赖注入的实现方式
1.1 闭包和偏函数实现依赖注入
在 Python 中,可以使用闭包和偏函数来实现依赖注入。以下是一个示例代码:
def bootstrap(..):
uow = unit_of_work.SqlAlchemyUnitOfWork()
# prepare a version of the allocate fn with UoW dependency captured in a closure
allocate_composed = lambda cmd: allocate(cmd, uow)
# or, equivalently (this gets you a nicer stack trace)
def allocate_composed(cmd):
return allocate(cmd, uow)
# alternatively with a partial
import functools
allocate_composed = functools.partial(allocate, uow=uow)
# later at runtime, we can call the partial function, and it will have
# the UoW already bound
allocate_composed(cmd)
闭包(如 lambda 表达式或命名函数)和 functools.p
超级会员免费看
订阅专栏 解锁全文
801

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



