Search code examples
pythonpython-asynciogenerator

How to make a function act as a generator only when used as one


One existing example of this is open which can be used in these two ways:

f = open("File")
print(f.readline())
f.close()

# ...and...

with open("File") as f:
  print(f.readline())

I intend to create a version of the asyncio.Lock class which allows you to not only acquire and release the lock manually but also to use a with block to wrap the code that requires the lock and release it automatically.


Solution

  • The thing you look for isn't a generator, but a context manager.

    You don't even need to implement one, This works:

    lock = asyncio.Lock()
    
    async def example():
        async with lock:
            # Your code here