On Fri, 2008-02-15 at 19:03 +0100, Duncan Webb wrote:
> If I'm understanding this correctly, The problem with callbacks and
> coroutines is that nothing can be returned so it can be tricky to make
> the code do what you want. For example, when someone selects a menu

Not exactly.

@coroutine-decorated functions return an InProgress object when they are
invoked.  When the underlying decorated function yields a value other
than kaa.NotFinished or an InProgress object (or if it raises an
exception), the InProgress object the call originally returned is
"finished" with that value (or exception).

So you can return values through coroutines by yielding them.

        @kaa.coroutine()
        def func():
           yield 42
        
        def handle_result(result):
           print "Async result:", result
        
        func().connect(handle_result)
        
Coroutines return InProgress objects, and these are pretty flexible
objects, and they can carry return values or exceptions.  They can be
yielded from other coroutines, causing the other coroutine to resume
once the InProgress it returned is finished.  It can then fetch the
value from it using get_result().  They can be connected to, as in the
above example, since InProgress objects are also signals.  InProgress
objects have an 'exception' attribute that is also a signal, and it is
emitted when the async function raises an exception.

An example:

        @kaa.coroutine()
        def do_something_with_func():
           try:
              result = yield func()
           except:
              print "func() raised an exception!"
              yield 
           assert(result == 42)
        
That syntax works with Python 2.5.  For python 2.4 compatible syntax:

        @kaa.coroutine()
        def do_something_with_func()   
           inprogress = func()
           yield inprogress
           try:
               result = inprogress.get_result()
           except:
              print "func() raised an exception!"
              yield
           assert(result == 42)

Now, it's also possible to block inside do_something_with_func():

        @kaa.coroutine()
        def do_something_with_func()
           try:
              result = func().wait()
           except:
              print "func() raised an exception!"
              yield
           assert(result == 42)

But as dischi said, it's better to yield the InProgress func() returns,
causing do_something_with_func() to automatically resume when func()
returns.

Have you read http://doc.freevo.org/2.0/SourceDoc/Async ?

Jason.


-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
Freevo-devel mailing list
Freevo-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/freevo-devel

Reply via email to