Home > Back-end >  Use pre-commit hook for black with multiple language versions for python
Use pre-commit hook for black with multiple language versions for python

Time:10-07

We are using pre-commit to format our Python code using black with the following configuration in .pre-commit-config.yaml:

repos:
  - repo: https://github.com/ambv/black
    rev: 20.8b1
    hooks:
      - id: black
        language_version: python3.7

As our packages are tested against and used in different Python versions (e.g. 3.7, 3.8, 3.9) I want to be able to use the pre-commit Hook on different Python versions. But when committing Code e.g. on Python 3.8, I get an error due to the language_version in my configuration (see above):

C:\Users\FooBar\Documents\Programmierung\foo (dev -> origin)
λ git commit -m "Black file with correct black version"
[INFO] Initializing environment for https://github.com/ambv/black.
[INFO] Installing environment for https://github.com/ambv/black.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
An unexpected error has occurred: CalledProcessError: command: ('c:\\users\\FooBar\\anaconda\\python.exe', '-mvirtualenv', 'C:\\Users\\FooBar\\.cache\\pre-commit\\repobmlg3b_m\\py_env-python3.7', '-p', 'python3.7')
return code: 1
expected return code: 0
stdout:
    RuntimeError: failed to find interpreter for Builtin discover of python_spec='python3.7'

stderr: (none)
Check the log at C:\Users\FooBar\.cache\pre-commit\pre-commit.log

How can I enable the pre-commit Hook on different Python-Versions e.g. only on Python 3?

Thanks in advance!

CodePudding user response:

one way would be to set language_version: python3 (this used to be the default for black) -- the actual language_version you use there doesn't matter all that much as black doesn't use it to pick the formatted language target (that's a separate option)

generally though, you shouldn't need to set language_version as either (1) the hook itself will set a proper one or (2) it will default to your currently running python

note also: you're using the twice-deprecated url for black -- it is now psf/black

__

disclaimer: I created pre-commit and I'm a black contributor

  • Related