1

In the docs for httpx.AsyncClient, it says

async with httpx.AsyncClient() as client:
    response = await client.get('https://example.org')

Is this necessary? Why can't I write:

async def get_client():
    return AsyncClient()

client = await get_client()

response = await client.get(...)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135

1 Answers1

2

You can certainly use the second form without putting it inside a with-block / context manager, but then you'll need to remember to manually call .aclose on the client once you are done with it.

https://www.python-httpx.org/api/#asyncclient

aclose(self)

Close transport and proxies.

From the httpx docs on using a Client:
https://www.python-httpx.org/advanced/#usage

The recommended way to use a Client is as a context manager. This will ensure that connections are properly cleaned up when leaving the with block:

with httpx.Client() as client:
   ...

While that guidance above shows a Client, the same applies for an AsyncClient:
https://www.python-httpx.org/async/#opening-and-closing-clients

Use async with httpx.AsyncClient() if you want a context-managed client.

async with httpx.AsyncClient() as client:
    ...

Depending on your use case, it may not be a problem for you. But if you are going to be integrating an httpx.AsyncClient into a larger application (ex. FastAPI), or have multiple instances of an httpx.AsyncClient sharing the same networking resources, or your application that use an httpx.AsyncClient is sharing the system with other applications that also use networking resources, it is good practice to make sure you call .aclose(). And putting it inside a context manager helps you to do that.

You can check out questions like this for reasons to close:
In aiohttp or httpx do I need to close session/client on application shutdown? :

In my experience, this may not always be the case, as I remember when programming with php, I had to manually kill all the database connections, otherwise on application restart I got "The process is already using that port".

If you really don't want or can't use a context manager:

Alternatively, use await client.aclose() if you want to close a client explicitly:

client = httpx.AsyncClient()
...
await client.aclose()
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135