Search code examples
pythonpre-commit-hookpre-commitpre-commit.com

pre-commit fails with ModuleNotFoundError: No module named 'yaml'


I am using pre-commit. In one of the hooks, I use a python script that imports the yaml library.

However, when I try to commit something, I get the following error on this hook :

ModuleNotFoundError: No module named 'yaml'

I don't understand what is the issue here as pyyaml is properly found in python

$ python3
Python 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>> 

Here is my .pre-commit-config.yml :

repos:
  # python hooks
  - repo: local
    hooks:
      - id: yaml-arrays-sort
        name: YAML Arrays Sort
        description: Sort arrays in YAML files
        entry: python scripts/yaml-arrays-sort.py
        pass_filenames: false
        language: python

Solution

  • language: python will cause pre-commit to create an isolated environment for your hook

    since you did not specify any additional_dependencies and because yaml is not a standard library module you're going to get a ModuleNotFoundError

    you need to make sure to install pyyaml, you can do that via:

        additional_dependencies: [pyyaml]
    

    disclaimer: I wrote pre-commit