Use pre-commit hook for black with multiple language versions for python
Asked Answered
P

1

8

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!

Potable answered 6/10, 2021 at 8:30 Comment(1)
I could solve the issue by using language_version: python3!Potable
T
15

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

Terrorism answered 6/10, 2021 at 12:44 Comment(4)
Thanks for your reply and the hint on the newest configuration. It works like a charm now!Potable
Maybe you could also add the configuration to your answer: black.readthedocs.io/en/stable/integrations/…Potable
If generally you shouldn't need to set language_version, why does Cord's link start with a comment # It is recommended to specify the latest version of Python supported by your project here?Airspace
@Airspace because they're wrongTerrorism

© 2022 - 2024 — McMap. All rights reserved.