asyncstdlib icon indicating copy to clipboard operation
asyncstdlib copied to clipboard

missing async_property

Open skewty opened this issue 3 years ago • 1 comments

Is there any reason why async property isn't part of this library? I see it in other libraries, but this one is more mature / complete and it is oddly missing it.

skewty avatar Jul 07 '22 05:07 skewty

Thanks for bringing this up. As a rule of thumb, if a builtin helper already works for the async case it is not duplicated. As far as I can tell, this is the case for property: all possible async cases are already covered by the standard property:

property has three cases: __get__ for instance.attribute, __set__ for instance.attribute = value and __del__ for del instance.attribute. An async_property would cover async variants of these.

  • There is no syntax for an async assignment or deletion, so these cases can be ignored outright.
  • An "async get" as await instance.attribute is actually await (instance.attribute) – the async part is separate from the getter part. One can achieve this by having a regular property getter that is async:
    import asyncio
    
    class Example:
        @property
        async def attribute(self):
            await asyncio.sleep(1)
            return "some value computed by an async function"
    
    async def test_get():
        instance = example()
        print(await instance.attribute)
    
    asyncio.run(test_get())
    

This works because property.__get__ is really simple and just makes a call; whether that call produces the result or instantiates a coroutine isn't a concern for property. In contrast, cached_property.__get__ needs to do something with the actual return value, so there need to be separate variants for sync (using the returned value directly) and async (await in the intermediate coroutine to get the value).


Using a synchronous interface to ferry through a coroutine-to-be-awaited is admittedly not something obvious. Perhaps adding a section to the docs to demonstrate and explain this would be useful?

maxfischer2781 avatar Jul 07 '22 09:07 maxfischer2781