Many Docker objects (like Volumes, Containers, etc.) can be used as Python context managers. When the execution leaves the with block, the object is automatically removed, even if an exception occurs.
from python_on_whales import docker
# The volume will be automatically removed after the block finishes
with docker.volume.create("random_name") as some_volume:
docker.run(
"postgres:9.6",
name="some-postgres",
envs={"POSTGRES_PASSWORD": "mysecretpassword"},
volumes=[(some_volume, "/var/lib/postgresql/data")],
detach=True,
)
# Perform operations with the volume here
# Volume is gone now