akl
akl

Reputation: 97

Pre-commit-hook for Python project

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.

Upvotes: 2

Views: 1747

Answers (3)

C.K.
C.K.

Reputation: 5498

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

Upvotes: 0

Andrii Dubonos
Andrii Dubonos

Reputation: 156

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]

Upvotes: 3

VonC
VonC

Reputation: 1323115

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?"

Upvotes: 0

Related Questions