gpt4 book ai didi

Python依赖注入(inject)

转载 作者:行者123 更新时间:2023-11-30 23:03:43 24 4
gpt4 key购买 nike

我有 3 个模块:A、B、C

A contains a set of classes that B has fetchers for.

B contains a bunch of singletons that just deal with caching created objects and providing them when requested. Essentially just fetchers.

C is a list of functions that requires instances of A.

我需要做的操作是:

C::SomeFunc():
B.getInstance("instance ID")


B::getInstance(someID: str) -> A:
-look at cache, which is either [] or {}
-if it is in cache, return that, else do: A(someID)

我的问题是,您将如何传递这些模块的实例?这个问题主要是由于我对Python的内存分配系统缺乏了解而引起的。

我可以按照基于构造函数的依赖注入(inject)的方式做一些事情来获取它们需要去的 A、B、C 的实例,然后拥有一些“master/god/controller”对象,将它们传递到它们需要的地方需要去 -

例如:

class god(object):
def __init__(self):
a = A()
b = B()
c = C(b)
.....
.....
class C(object):
def __init__(self, B_instance):
self.B = B_instance
def SomeFunc(self, instanceID):
self.B.getInstance(instanceID)

但这看起来像是一个黑客。

有什么建议吗?

谢谢!

最佳答案

我见过一些在 there on PyPI 上提供实例提供程序的软件包如果这就是您正在寻找的。就我个人而言,我不想处理另一个对象来获取实例。所以我为此创建了自己的库(仅限 Python 3)。您只需要 @inject 和注释。

from py3njection import inject
from some_package import ClassToInject

class Demo:
@inject
def __init__(self, object_to_use: ClassToInject):
self.dependency = object_to_use

demo = Demo()

可以找到here 。它基本上在每次调用该方法时都会创建一个新实例。

这样测试很容易,因为您只需将模拟作为参数传递给您的函数/方法进行单元测试。

我也添加了@singleton

如果您需要更多实例化方法,例如您所描述的缓存系统,文档将解释如何轻松实现您自己的实例化方法。与缓存相关的所有内容都将在工厂中处理,依赖于它们的对象不必知道如何获取它们。

但是如果您使用的是 Python 2 或者您需要对注入(inject)进行更多控制,this could work too 。但您仍然需要操纵提供者。

关于Python依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com