I'm developing python code on a Windows machine. When I have a new python package I am working on I create a virtual environment named .venv
with python -m venv .venv
. I activate the venv using .venv\Scripts\activate
. When working on the package I install package dependencies such as numpy
with (.venv) C:\...\my_package> pip install numpy
.
I am trying to figure out how I should install the pre-commit
package so that I can use pre commit hooks during version control of the package source code and related materials.
One workflow (following the philosophy of never installing anything in the base python install) would be to
- Activate the virtual environment
- install
pre-commit
into the virtual environment - write the
.pre-commmit-config.yaml
file - run
pre-commit install
in the package/repo directory - Run
git
commands, ensuring the virtual environment is activated (otherwisepre-commit
will not be able to run properly)
The major downside to this strategy is that it REQUIRES the virtual environment to be activated for git commands to work. This is a bit strange since normally you don't need python for git to work, and you might even be version controlling a repository that is not even python code!
The alternative workflow would be
- install
pre-commit
into the global python installation. Nowpre-commit
is available as a command line command anywhere on the system. - write the
.pre-commmit-config.yaml
file - run
pre-commit install
in the package/repo directory - Run
git
commands,pre-commit
should always work.
The downside here is you're messing with your global python installation and you may run into weirdness if e.g. you have multiple python installations on your system.
A similar strategy might be to use a tool like pipx
to do a "global" installation of pre-commit
.
What is a recommended installation strategy for pre-commit
?
One nice solution to this problem is to use pipx.
pipx
essentially provides a middle ground between installing nothing to the global python installation and installing everything to the global python installation.pipx
is installed into the global python installation and then you usepipx
to (1) install (and manage) python-based command line tools (such aspre-commit
) within isolated virtual environments and (2) expose those command line tools to the global terminal command namespace. The workflow in this case is:python -m pip install --user pipx
to installpipx
to the global python.pipx ensurepath
to make sure path is setup correctly.pipx install pre-commit
pre-commit install
in the git repo of interest.pre-commit-config.yaml
in the git repo of interestgit
commands should work usingpre-commit
(which uses thepre-commit
installed bypipx
) on the repo of interest, whether or not the virtual environment is activated.