I would like to know the Git checkout version of my Python code when running the code.

The standard way to achieve this is to use clean/smudge filters. However, the standard examples I found are quite basic and use a mixture of Perl/Ruby/Shell scripts.

Here is one script that can be added to a Python project, and which will work both as a clean and smudge filter:


This script will transform stdin to expand some keywords with git version/author/date information. You can specify the option --clean to remove this information before commit.

Setup: #

__version__ = ""
__author__ = ""
__email__ = ""
__date__ = ""
  • Add this file to the repository:
git add versioning.py
git add version.py
git commit -m "added versioning files"
  • Run:
git config filter.versioning.smudge 'python versioning.py'
git config filter.versioning.clean 'python versioning.py --clean'
echo 'version.py filter=versioning' >> .gitattributes
git add .gitattributes
git commit -m "Changed .gitattributes"

Note that the path to versioning.py must be relative to the root of your repository.

You update the file version like this (this can be a post-checkout hook, too -- see below):

rm version.py
git checkout version.py
cat version.py

This should give you the following updated version.py file:

__version__ = "4d5ca36"
__author__ = "[Your Name]"
__email__ = "[Your Email]"
__date__ = "Fri Nov 8 11:06:28 2013 +0000"

Installing Hooks #

Now, I might forget updating the version file every time I change something. The way to do this in git is to add hooks. I added two hooks to do this, a post-checkout hook and a post-commit hook. I used the same file (the files will be run in the root directory of the repository):


cat version.py | python versioning.py --clean | python versioning.py > version.py

Now, every time I commit or checkout, my version number will be updated automatically.