Python asynchronous callbacks and generators

前端 未结 3 1855
生来不讨喜
生来不讨喜 2021-02-04 12:13

I\'m trying to convert a synchronous library to use an internal asynchronous IO framework. I have several methods that look like this:

def foo:
  ....
  sync_cal         


        
3条回答
  •  甜味超标
    2021-02-04 13:09

    You need to make function foo also async. How about this approach?

    @make_async
    def foo(somearg, callback):
        # This function is now async. Expect a callback argument.
        ...
    
        # change 
        #       x = sync_call1(somearg, some_other_arg)
        # to the following:
        x = yield async_call1, somearg, some_other_arg
        ...
    
        # same transformation again
        y = yield async_call2, x
        ...
    
        # change
        #     return bar
        # to a callback call
        callback(bar)
    

    And make_async can be defined like this:

    def make_async(f):
        """Decorator to convert sync function to async
        using the above mentioned transformations"""
        def g(*a, **kw):
            async_call(f(*a, **kw))
        return g
    
    def async_call(it, value=None):
        # This function is the core of async transformation.
    
        try: 
            # send the current value to the iterator and
            # expect function to call and args to pass to it
            x = it.send(value)
        except StopIteration:
            return
    
        func = x[0]
        args = list(x[1:])
    
        # define callback and append it to args
        # (assuming that callback is always the last argument)
    
        callback = lambda new_value: async_call(it, new_value)
        args.append(callback)
    
        func(*args)
    

    CAUTION: I haven't tested this

提交回复
热议问题