If I understand the question correctly, the answer is that you cannot; There is no way to write a magic method as an explicit coroutine and behave correctly if it is implicitly called Python. This is a known limitation of explicit coroutines.
So, if you have this:
class SomeObj:
@coroutine
def __contains__(self, obj):
exists = yield self.somemethod(obj)
return exists
This will not do what you want:
o = SomeObj()
'x' in o
Python does not expect to __contains__be a coroutine and will not behave correctly if it is - the core of the language does not know anything about tornadoor asyncio, or any other frameworks is used to implement these coroutines and will not integrate correctly with them. The same applies to other implicitly called magic methods, such as __init__, __getattr__etc.
, , yield yield from ( ). , (, , @classmethod) SomeObj, , , __init__:
@coroutine
def create_someobj():
s = SomeObj()
yield s.slow_init()
return s
coroutine - contains , in. , , .
, ; PEP 492, , for-loops ( , ). , Python 3.5, :
async def some_func():
s = SomeObj()
async for item in s:
print(item)
async with SomeObj() as s:
await s.some_method()