Skip to content

Safety Warning (Dry Runs and Backups)

Why this matters

Automation can:

  • delete thousands of files instantly
  • overwrite important documents
  • send emails/messages to the wrong people

You want guardrails.

Dry run pattern

A dry run prints what would happen without doing it.

dry_run_pattern.py
from pathlib import Path
 
 
def delete_tmp_files(folder: Path, dry_run: bool = True):
    for path in folder.rglob("*.tmp"):
        if dry_run:
            print("[DRY RUN] would delete", path)
        else:
            print("deleting", path)
            path.unlink()
 
 
delete_tmp_files(Path("./demo"), dry_run=True)
dry_run_pattern.py
from pathlib import Path
 
 
def delete_tmp_files(folder: Path, dry_run: bool = True):
    for path in folder.rglob("*.tmp"):
        if dry_run:
            print("[DRY RUN] would delete", path)
        else:
            print("deleting", path)
            path.unlink()
 
 
delete_tmp_files(Path("./demo"), dry_run=True)

Use a sandbox folder

  • Copy a small sample dataset
  • Run scripts there first

Always keep backups

At minimum:

  • zip the folder before modifying it
  • store backups outside the working directory

Add logging (not print)

basic_logging.py
import logging
 
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s"
)
 
logging.info("starting job")
basic_logging.py
import logging
 
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s"
)
 
logging.info("starting job")

Add confirmations for destructive actions

confirm_delete.py
from pathlib import Path
 
folder = Path("./demo")
ans = input(f"Really delete all .tmp files under {folder}? (yes/no) ")
if ans.strip().lower() != "yes":
    raise SystemExit("Cancelled")
confirm_delete.py
from pathlib import Path
 
folder = Path("./demo")
ans = input(f"Really delete all .tmp files under {folder}? (yes/no) ")
if ans.strip().lower() != "yes":
    raise SystemExit("Cancelled")

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did