2

How do I remove print statements in a Python project using pre-commit hook before checking in code to GitHub? Currently, I use black and flake8 pre-commit hooks. But they don't seem to have the option to check and remove print statements before checking in code.

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
akl
  • 77
  • 3
  • 9

3 Answers3

3

You could use flake8 plugin to check for print statements.

https://pypi.org/project/flake8-print/

Just add to your pre-commit config:

  - repo: https://gitlab.com/pycqa/flake8
    rev: <desired-rev>
    hooks:
      - id: flake8
        additional_dependencies: [flake8-print]
Andrii Dubonos
  • 106
  • 1
  • 5
  • The "canonical" link (based on the repos metadata) should be to [github](https://github.com/pycqa/flake8), not gitlab. – CoatedMoose May 11 '23 at 16:41
0

Since the pre-commit framework only calls flake8, you would need to check its configuration to see if there is any setting which would trigger a print statement deletion (as opposed to error/violation codes)

Since that is not supported by flake8 itself, you would need to develop a plugin to flake8 in order to act on those error and delete the print lines.
If you do, don't forget to add the changes, as explained in "Can you change a file content during git commit?"

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

remove-print-statements finally solved my problem

repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
    -   id: end-of-file-fixer
    -   id: trailing-whitespace
-   repo: https://github.com/pycqa/flake8
    rev: 6.0.0
    hooks:
    - id: flake8
-   repo: https://github.com/dhruvmanila/remove-print-statements
    rev: v0.5.1  # Replace with latest tag on GitHub
    hooks:
    -   id: remove-print-statements
        args: ['--verbose']

I tried flake8-print doesn't work

$ flake8 --version
6.0.0 (flake8-print: 5.8.8, mccabe: 8.7.8, pycodestyle: 2.10.0, pyflakes: 3.0.1) CPython 3.11.3 on Darwin
C.K.
  • 4,348
  • 29
  • 43