The operation of an async context manager depends on the method calls
and can be implemented to create coroutines in a program. These coroutines are extremely helpful when working with repetitive tasks that require resources to be well defined within a scope.
One key thing to remember is that not all context managers must be async ones. Async context managers should only be there if you want to await inside the
enter
andexit
blocks.
To make use of the async context manager, prepend the keyword async
behind the target function.
The example below shows how to make the connection function asynchronous.
async with Connection('localhost', 500) as conn:
When using the async context manager, the following functions should be used:
_aenter_()
function in place of _enter_()
._aexit_()
function in place of _exit_()
function. The parameters for _aexit_()
are exactly similar to _exit_()
.Both of these functions should be defined using the async def method.
The following code gives the complete implementation of the async method to set up a connection.
class Connection:def _init_(self, host, port): #initializing the objectself.host = hostself.port = portasync def _aenter_(): #setting up a connectionself.conn = await get_conn(self.host, self.port)return connasync def _aexit_(self, exc_type, exc, tb): #closing the connectionawait self.conn.close()async with Connection('localhost', 500) as conn:# addfunctionality here
_aenter()_
function within the class. This function is used to set up the connection._aexit()_
function. This function is called when tearing down the connection.The above functionality can be implemented using the contextlib library as well.
Free Resources