简体   繁体   中英

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 . In order to satisfy its dependency, it calls make_a with a callback to make_b . Once a is made, then make_b is called again and b is made.

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?

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.

Here you have an observer example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM