types-docker
types-docker is a type stub package providing accurate annotations for the `docker` Python library. It enables static type checkers like MyPy or Pyright to verify code using the Docker SDK for Python, ensuring type safety and improving developer experience. This package is part of the `typeshed` project and tracks the `docker` library's versions, aiming for daily updates.
Warnings
- breaking The `docker` library (for which `types-docker` provides stubs) dropped support for Python 2.7 with version 2.0.0 and Python 3.6 with version 7.x. Ensure your Python environment meets the minimum `docker` library requirements.
- breaking The `docker` library was renamed from `docker-py` around version 2.0.0. Installing `docker-py` instead of `docker` will lead to `ModuleNotFoundError` when importing `docker`.
- gotcha When both an installed library (like `docker`) has its own inline type hints and a stub package (`types-docker`) is present, type checkers typically prioritize the stub package. This can lead to unexpected type-checking errors if the stub package's types differ significantly or are more strict than the inline types in the library's source code, or if the stub version is mismatched with the runtime library version.
- deprecated Native type hinting for generic collections (e.g., `list[str]` instead of `typing.List[str]`) became available in Python 3.9. While older `typing` module imports still work, it's recommended to use native generics for cleaner and more Pythonic code when using Python 3.9+.
Install
-
pip install types-docker
Imports
- docker
import docker
- DockerClient
from docker import DockerClient
Quickstart
import docker
import os
def main():
# Connect to the Docker daemon using environment variables or default socket
# Requires Docker Desktop or daemon running.
# For auth, Docker typically uses local socket or environment variables like DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH.
# No specific auth key needed in os.environ for basic local setup.
client: docker.DockerClient = docker.from_env()
print("Docker client connected.")
# Run a simple 'hello-world' container
print("Running 'hello-world' container...")
try:
container = client.containers.run('hello-world', remove=True, detach=True)
print(f"Container ID: {container.id}")
# Wait for container to finish and print its logs
container.wait()
logs = container.logs().decode('utf-8')
print("Container logs:")
print(logs)
print("Container finished and removed.")
except docker.errors.ContainerError as e:
print(f"Container error: {e}")
except docker.errors.ImageNotFound as e:
print(f"Image not found: {e}. Please ensure 'hello-world' image is available or can be pulled.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example: List all running containers (if any)
print("\nListing running containers:")
for c in client.containers.list():
print(f" - {c.name} ({c.status})")
if __name__ == "__main__":
main()