5

I want a class along the lines of the following

Foo(object):
    @property
    @asyncio.coroutine
    def bar(self):
        # This will need to run some blocking code via loop.run_in_executor()
        return 'bar'

And then I want to access the properties without having to a yield from

# In a loop...
foo = Foo()
foo.bar    #This will return a generator object, but I want it to return 'bar'.
yield from foo.bar     #This will return 'bar', but I don't want to do the yield from.

Is such a thing possible?

neRok
  • 995
  • 9
  • 21
  • 1
    the only way to run the coroutine generator is to use 'yield from', whereby the calling coroutine effectively drives it, else using something like asyncio.async to drive it. Otherwise its just an 'inert' generator object per your observations. – songololo Jul 21 '15 at 07:28
  • @shongololo Might as well make that an answer. – dano Jul 21 '15 at 14:48

1 Answers1

4

The way to run a coroutine generator is to use yield from (await in Python 3.5) from another coroutine. The yield from (await) is what allows one coroutine to drive another coroutine, which normally means that you have chains of linked coroutines that are ultimately driven by the event loop.

Another option is to use a Task-like wrapper like asyncio.async (ensure_future() in Python 3.5) to drive the coroutine.

Without one of the above, it's just an inert generator object (or coroutine, in Python 3.5) per your observations.

songololo
  • 4,724
  • 5
  • 35
  • 49
  • Thanks. So it is apparent that the property cannot be a coroutine if I do not want to yield from the property. Are you able to expand your answer to show how to create a task inside a normal function (not a coroutine function) which will run the blocking code in another thread, so that the main thread/loop can continue? I will update my question to reflect this. Edit: Actually, I had better make a new, more specific question. I think this one is answered. – neRok Jul 22 '15 at 03:07
  • Here is my new question: https://stackoverflow.com/questions/31553746/how-to-add-a-coroutine-task-to-the-loop-from-a-blocking-function-already-runni – neRok Jul 22 '15 at 04:15