2015-07-21 31 views
2

我想沿着以下使用@property装饰器与@ asyncio.coroutine没有做可能的产量?

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

线一类,然后我想,而不必一个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. 

访问属性是这样的事情可能吗?

+1

运行协程生成器的唯一方法是使用'yield from',由此调用协程有效地驱动它,否则使用诸如asyncio.async之类的东西来驱动它。否则,它只是一个“惰性”的发电机对象,根据你的观察。 – shongololo

+0

@shongololo不妨做出答案。 – dano

回答

3

运行协程生成器的方法是从另一个协同程序中使用yield from(Python 3.5中的await)。 yield fromawait)是什么允许一个协程驱动另一个协程,这通常意味着你有最终由事件循环驱动的链接协程链。

另一种选择是使用像asyncio.async(Python 3.5中的ensure_future())这样的Task-like包装来驱动协程。

没有上述内容,根据您的观察结果,它只是一个惰性生成器对象(或协程,在Python 3.5中)。

+0

谢谢。所以很显然,如果我不想从房产中牟利,房产就不可能成为协同工程。你能扩展你的答案来展示如何在一个普通函数(不是协程函数)内创建一个任务,它将在另一个线程中运行阻塞代码,这样主线程/循环可以继续吗?我会更新我的问题以反映这一点。编辑:其实,我最好做一个新的,更具体的问题。我认为这个答案。 – neRok

+0

这是我的新问题:https://stackoverflow.com/questions/31553746/how-to-add-a-coroutine-task-to-the-loop-from-a-blocking-function-already-runni – neRok

相关问题