Skip to main content

Python, Git and a post-checkout hook

When switching between branches with different sets of .py files it can easily happen that code containing broken imports is slipping through unnoticed. By broken import I mean import foo with no foo.py around on that branch. Such thing can happen, as the .pyc file is still laying around. To prevent it you could stuff this into .git/hooks/post-checkout:

#! /usr/bin/env bash
find . -name '*.pyc' -print -delete | \
   sed 's|^|[post-checkout] Deleting |'

or a slightly smarter version of it:

#! /usr/bin/env bash
find . -type f -name '*.pyc' -exec bash -c '
pyc_file="{}"
py_file=${pyc_file/\.pyc/.py}
if [[ ! -f "${py_file}" ]]; then
    rm -v "${pyc_file}"
fi
' \; | \
sed 's|^|[post-checkout] |'