pythongitpycharmcode-standards

Code standards check before commit in PyCharm


I would like to have some analysis done on Python code before I commit, to gently “enforce” the standards.

I would like to have a check such as:

( inside the team we could expand the list as needed)

Those should be only as warnings, because I don’t want to prevent commit if needed.

I was looking into pycharm settings/version control/commit/analyse before commit/ But this is working only sometimes and only accepts regex.

Is there any better and simpler way to do this?


Solution

  • You can use one (or more) of a standard set of Python linters, such as flake8, pylint, or black in this context. It's better to use a separate linter with the configuration checked in rather than particular editor settings because different people may use different editors. However, most major editors can invoke external lint tools in a standard way and show the linting output in the editor. This allows the developer to see any relevant changes as they type and correct them early on.

    You mentioned that you don't want to fail the commit, so you can write a pre-commit hook that looks like this:

    #!/bin/sh
    
    # Replace the line below with your preferred lint tool.
    MY-LINT-TOOL
    exit 0
    

    This means that the check will always succeed, since it exits zero, but it will run the linter and show the output. This is the standard way to do this with Git, but it isn't necessarily guaranteed that all editors will show that output; that is a quality of implementation issue.

    Note that there is no way to automatically install hooks with the repository, because hooks can execute arbitrary code and that would be a security vulnerability. You can provide them for folks who want to use them, and provide a script to install them, but you should also consider and respect that some people will not want to use them. If you need to enforce a policy, that must be done on the server side and is typically done as part of a CI job; client-side hooks can be trivially bypassed with no trace.

    Which linter you decide to use is up to you and depends on your particular needs. Most of them will follow PEP 8 style rules, which are customary for Python and I would recommend those (because you should generally prefer to use the language's default style rules, whatever they are, when the language has a strong default style). You may decide to use multiple options, which might also be useful if you have a mix of languages (such as in a web app). However, running all of them on every commit might be slow, so it would be good to minimize the number running in the hook.