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-commitinto the virtual environment - write the
.pre-commmit-config.yamlfile - run
pre-commit installin the package/repo directory - Run
gitcommands, ensuring the virtual environment is activated (otherwisepre-commitwill 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-commitinto the global python installation. Nowpre-commitis available as a command line command anywhere on the system. - write the
.pre-commmit-config.yamlfile - run
pre-commit installin the package/repo directory - Run
gitcommands,pre-commitshould 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.
pipxessentially provides a middle ground between installing nothing to the global python installation and installing everything to the global python installation.pipxis installed into the global python installation and then you usepipxto (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 pipxto installpipxto the global python.pipx ensurepathto make sure path is setup correctly.pipx install pre-commitpre-commit installin the git repo of interest.pre-commit-config.yamlin the git repo of interestgitcommands should work usingpre-commit(which uses thepre-commitinstalled bypipx) on the repo of interest, whether or not the virtual environment is activated.