Hopefully the following code explains what I want to do better than the question title.
import asyncio
import time
loop = asyncio.get_event_loop()
class Foo(object):
def __init__(self, num):
self.num = num
@property
def number(self):
# Somehow need to run get_number() in the loop.
number = self.get_number()
return number
@asyncio.coroutine
def get_number(self):
yield from loop.run_in_executor(None, time.sleep, self.num)
return self.num
@asyncio.coroutine
def runner(num):
print("getting Foo({})".format(num))
foo = Foo(num)
yield from asyncio.sleep(1)
print("accessing number property of Foo({})".format(num))
number = foo.number
print("Foo({}) number is {}".format(num, number))
tasks = [
asyncio.async(runner(3)),
asyncio.async(runner(1)),
]
go = loop.run_until_complete(asyncio.wait(tasks))
I can't work out what to do in the number
function, where the comment is. I've tried all sorts of things, but in reality I've just "been throwing **** at the wall and hoping something sticks".
This is a follow-up to this question. I want to access the property without doing a yield from
, as I need to access the property from a template (eg mako), and having yield from
written everywhere is not ideal (probably not even possible considering mako is probably blocking). In a perfect world, I would have all of this running with a reify decorator.
If I wanted to use yield from
, the code would be quite simple.
class Foo(object):
def __init__(self, num):
self.num = num
@property
@asyncio.coroutine
def number(self):
yield from loop.run_in_executor(None, time.sleep, self.num)
return self.num
@asyncio.coroutine
def runner(num):
print("getting Foo({})".format(num))
foo = Foo(num)
yield from asyncio.sleep(1)
print("accessing number property of Foo({})".format(num))
number = yield from foo.number
print("Foo({}) number is {}".format(num, number))
#getting Foo(3)
#getting Foo(1)
#accessing number property of Foo(3)
#accessing number property of Foo(1)
#Foo(1) number is 1
#Foo(3) number is 3
I found this answer on the topic, but I can't see how adding done callbacks will work with my workflow.