docker / docker/docker-py

Make `DockerClient` a Context Manager

Open
#2,808 5 comments 4 reactions 1 assignee View on GitHub

@feliperuhland is already working on this.

Since Apr 8, 2021.

Dominant language
Python
Stars
7.2k
Forks
1.7k
Avg merge
13d 8h
Merged PRs (30d)
2

Description

It's not obvious that DockerClient needs to have its close() method called to clean up resources, which can lead to unclosed sockets. We noticed this using asyncio and pytest together, which complains about unclosed sockets when tearing down test sessions.

Since DockerClient is wrapping ApiClient, and ApiClient inherits its close() method from requests.Session, it's not even obvious from a brief glance source what close() is for.

I expect that ApiClient is already a Context Manager, since it would inherit __enter__ and __exit__ from requests.Session, so the low-level API already has this behaviour.

To make it easier to avoid mistakes, DockerClient could have __enter__ and __exit__ methods added, identical to requests.Sessions, which would allow safer usage patterns such as

with docker.from_env() as docker_client:
 # Do stuff with docker_client

when that's feasible.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.