Suppose I have a list/tuple of strings,
COLOURS = [
"White",
"Black",
"Red"
"Green",
"Blue"
]
for c in COLOURS:
# rest of the code
Sometimes I forget placing a comma after each entry in the list ("Red"
in the above snippet). This results in one "RedGreen"
instead of two separate "Red"
and "Green"
list items.
Since this is valid Python, no IDE/text editor shows a warning/error. The incorrect value comes to the limelight only during testing.
What writing style or code structure should I use to prevent this?
You're incorrect that "no IDE/text editor shows a warning/error". Pylint can identify this problem using rule implicit-str-concat (W1404) with flag check-str-concat-over-line-jumps. (And for that matter, there are lots of things that are valid Python that a linter will warn you about, like bare except:
for example.)
Personally, I'm using VSCode, so I enabled Pylint via the Python extension (python.linting.pylintEnabled
) and set up a pylintrc like this:
[tool.pylint]
check-str-concat-over-line-jumps = yes
Now VSCode gives this warning for your list:
Implicit string concatenation found in list pylint(implicit-str-concat) [Ln 4, Col 1]
Lastly, there are probably other linters that can find the same problem, but Pylint is the first one I found.