2015-07-21 57 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