Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It there any default asynchronious null context manager in python3.7+?

I would like to create optional asynchronious semaphore.
In case of asyncio.Semaphore does not support None values, i decided to create asyncio.Semaphore, if connections limit is specified, else - some kind of dummy object
There is a contextlib.nullcontext, but it supports only synchorious with
I`ve created my own dummy:

@contextlib.asynccontextmanager
async def asyncnullcontext():
    yield None

It there any default asynchronious null context manager?

like image 297
Trizalio Avatar asked Apr 28 '20 11:04

Trizalio


2 Answers

It there any default asynchronious null context manager?

You can use contextlib.AsyncExitStack().

ExitStack() was similarly the way to create a quick-and-dirty null context manager before the introduction of nullcontext.

like image 132
user4815162342 Avatar answered Oct 23 '22 07:10

user4815162342


Starting from Python 3.10+, contextlib.nullcontext() can be used as both a synchronous and asynchronous context manager.

from contextlib import nullcontext

def works():
    with nullcontext():
        pass

async def works_too():
    async with nullcontext():
        pass

(This question explicitly mentions Python 3.7 but I guess more and more people may find it without specifically needing that version, hence this answer)

like image 1
Roméo Després Avatar answered Oct 23 '22 07:10

Roméo Després