Search code examples
pythonmypypre-commitpre-commit.com

pre-commit using mypy specify venv cross-platform


I'm using pdm, and each project has its own .venv. When using mypy, I need to specify venv like mypy --python-executable ./.venv/Scripts/python.exe . on windows or mypy --python-executable ./.venv/bin/python . on linux.

Now I want to use pre-commit and put mypy in the hooks. I write

- repo: https://github.com/pre-commit/mirrors-mypy
  rev: v1.11.1
  hooks:
  - id: mypy

In this way, I can't commit any code because I would fail in mypy as I haven't specified venv. So I have to

  rev: v1.11.1
  hooks:
  - id: mypy
    args: ["--python-executable", "./.venv/Scripts/python"]

on my windows computer. Now everything goes well, but I immediately realize that it would fail on linux because there is no .venv/Scripts/python but .venv/bin/python. So, how should I use mypy in pre-commit cross-platform?


Solution

  • you're sorta missing the point of pre-commit here (it is meant to provision and manage your environments for you so your contributors don't have to go through N incantations to get linting working) -- and maybe mypy as a hook isn't a good fit for your use cases.

    you might be better with language: system (and just call your virtualenv's mypy directly) but that's explicitly unsupported territory (as is depending on the installed state of the repository-under-test -- since that's unprovisioned)

    another idea would be to write a script which handles your platform differences for you (with entry: ./your-script) -- but again that still does your contributors a disservice in that they have to manually set up ./.venv properly in order to run the linters

    it's probably best to not use mypy via pre-commit in your case -- or manage all of your typed dependencies through additional_dependencies


    disclaimer: I wrote pre-commit