Skip to content

async/await support doesn't work with Twisted #215

@dreid

Description

@dreid

I'm not sure I expect cached-property to do anything about this, but it appears to be an undocumented limitation.

My (limited) understanding is that this is part cached_property limitation and part a limitation of Twisted's Deferred (it does not support being awaited from an asyncio coroutine which is what cached_property is trying to do).

Hopefully one of the active Twisted developers (or someone else) can chime in with how cached_property might handle this.

Versions:

  • Python 3.8.2
  • Twisted==20.3.0
  • cached-property==1.5.1

Reproduction:

from cached_property import cached_property

class Monopoly(object):

    def __init__(self):
        self.boardwalk_price = 500

    @cached_property
    async def boardwalk(self):
        self.boardwalk_price += 50
        return self.boardwalk_price

async def print_boardwalk():
    monopoly = Monopoly()
    print(await monopoly.boardwalk)
    print(await monopoly.boardwalk)
    print(await monopoly.boardwalk)

print("With asyncio")
print("------------")
import asyncio
asyncio.get_event_loop().run_until_complete(print_boardwalk())
print("------------")

print("With twisted")
print("------------")
from twisted.internet.defer import ensureDeferred
from twisted.internet.task import react
react(lambda _: ensureDeferred(print_boardwalk()))
print("------------")

Results:

With asyncio
------------
550
550
550
------------
With twisted
------------
main function encountered error
Traceback (most recent call last):
  File ".ve/lib/python3.8/site-packages/twisted/internet/task.py", line 909, in react
    finished = main(_reactor, *argv)
  File "<stdin>", line 29, in <lambda>
    
  File ".ve/lib/python3.8/site-packages/twisted/internet/defer.py", line 911, in ensureDeferred
    return _cancellableInlineCallbacks(coro)
  File ".ve/lib/python3.8/site-packages/twisted/internet/defer.py", line 1529, in _cancellableInlineCallbacks
    _inlineCallbacks(None, g, status)
--- <exception caught here> ---
  File ".ve/lib/python3.8/site-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks
    result = g.send(result)
  File "<stdin>", line 15, in print_boardwalk
    
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/coroutines.py", line 127, in coro
    res = yield from res
builtins.RuntimeError: await wasn't used with future

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions