[英]What are the drawbacks to using callbacks for satisfying dependencies? And, is this an anti-pattern?
I have two modules: 我有两个模块:
#module_a
def make_a(cb = None):
global a
a = 1 # It takes a very long time to make "a", so it is stored as a global in module_a.
if cb != None:
cb()
And, 和,
#module_b
import module_a
def make_b():
global b
#In order to make "b", we need module_a.a, however there is no guarantee it has been made.
if 'a' not in dir(module_a):
module_a.make_a(make_b)
return
else:
b = module_a.a + 1
make_b()
print(b) # 2
In the above code, the function make_b
in module_b
makes something named b
, which depends on something named a
in module_a
. 在上面的代码中,函数
make_b
在module_b
使得命名的东西b
,它依赖于一个名为东西a
在module_a
。 In order to satisfy its dependency, it calls make_a
with a callback to make_b
. 为了满足其依赖性,它使用
make_a
的回调调用make_b
。 Once a
is made, then make_b
is called again and b
is made. 一旦创建
a
,则再次调用make_b
并生成b
。
This pattern makes sense to me, but I am wondering if this is a generally accepted approach to doing this or if it is an anti-pattern. 这种模式对我来说很有意义,但是我想知道这是执行此操作的公认方法还是反模式。
Is there a more canonical approach to satisfying such a dependency in Python ie, the Pythonic way? 是否有更规范的方法来满足Python中的这种依赖关系,即Pythonic方式?
To do this in a "Pythonic" way you should introduce an Observer pattern that emits an event once a is computed and b should subscribe to a in order to be called after a is finished. 要以“ Pythonic”方式执行此操作,您应该引入一个Observer模式,该模式一旦计算出a便会发出事件,并且b应当订阅a以便在a完成后被调用。
Here you have an observer example 这里有一个观察者的例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.