-1

I use Python since 2001, and I am very used to %s string formatting.

In my current environment code should be formatted with f-strings.

How to automatically check my code, so I don't accidentally use my old habit?

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
guettli
  • 25,042
  • 81
  • 346
  • 663
  • 1
    Since you need to wire up some form of automation to run the check, why not go forward and make that automation to actually convert all format strings to f-strings with https://github.com/ikamensh/flynt ? – rasjani Feb 22 '21 at 11:30
  • @rasjani this is a huge code base, cleaning the whole thing is not my current task. But I can suggest this at the next meeting. – guettli Feb 22 '21 at 12:29

2 Answers2

1

I use pyupgrade as a pre-commit hook https://github.com/asottile/pyupgrade

Sample .pre-commit-config.yaml:

-   repo: https://github.com/asottile/pyupgrade
    rev: v2.10.0
    hooks:
    -   id: pyupgrade
Thomas Grainger
  • 2,271
  • 27
  • 34
-1

You can use this pre-commit.com config

.pre-commit-config.yaml:

  - repo: local
    hooks:
      - id: dont-use-%s-formatting
        name: Do not use %s formatting any more
        entry: \%s
        language: pygrep
        types: [text]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
guettli
  • 25,042
  • 81
  • 346
  • 663
  • Is that just a regex to detect literal `%s`? If so, there are a lot of things it would miss (see https://docs.python.org/3/library/stdtypes.html#old-string-formatting). Also you still need to use `printf`-style format strings for e.g. logging. – jonrsharpe Feb 22 '21 at 10:50
  • @jonrsharpe yes, this is just a regex detecting `%s`. Of course this won't catch a lot of other old-string-formatting, but `%s` is the one which used the most. And there could be false-positives, but then I can use `SKIP=... git commit`. I like the solution. Do you know a better solution? – guettli Feb 22 '21 at 11:24
  • 1
    A brief Google suggests e.g. https://pypi.org/project/flake8-printf-formatting/ – jonrsharpe Feb 22 '21 at 11:30