Cleanup

2 snippets across 2 stacks - Docker, Python

DKDocker

Dangling Images & Orphan Volumes

DK · Common Mistakes
Syntax
# Check dangling images:
docker images -f dangling=true
# Check orphan volumes:
docker volume ls -f dangling=true
Example
# Frequent rebuilds leave untagged images:
docker images -f dangling=true
# REPOSITORY  TAG     SIZE
# <none>      <none>  450MB
# <none>      <none>  450MB

# Clean them:
docker image prune
docker volume prune

Note Every time you rebuild with the same tag, the old image loses its tag and becomes <none>:<none>. These pile up fast. Volumes from removed containers also linger. Schedule regular prune commands or add them to your CI cleanup steps.

PYPython

else & finally

PY · Error Handling
Syntax
try:
    ...
except:
    ...
else:
    ...
finally:
    ...
Example
def safe_divide(a: float, b: float) -> float | None:
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    else:
        print(f"Result: {result}")
        return result
    finally:
        print("Division attempted")

safe_divide(10, 3)
safe_divide(10, 0)
Output
Result: 3.3333333333333335
Division attempted
Cannot divide by zero
Division attempted

Note else runs only when no exception occurred. finally always runs, even after return statements. Use else to keep the try block minimal.

Frequently asked questions

How does Docker handle cleanup?
This task is covered in 2 stacks on this page: Docker, Python. The "Dangling Images & Orphan Volumes" snippet in Docker uses `# Check dangling images:`.
Which command does the Docker example use?
The "Dangling Images & Orphan Volumes" snippet uses `# Check dangling images:`, from the Common Mistakes section of the Docker cheat sheet.
Which stacks cover "cleanup" on this page?
Docker, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Dangling Images & Orphan Volumes": Every time you rebuild with the same tag, the old image loses its tag and becomes <none>:<none>. These pile up fast. Volumes from removed containers also linger. Schedule regular prune commands or add them to your CI cleanup steps.