Pylint: Unnecessary warning with regex groups

Created on 26 Apr 2017  路  3Comments  路  Source: PyCQA/pylint

Steps to reproduce

  1. Enter the following code
import re
emendation = re.compile(r"\({(.*){\)", re.DOTALL)
string = "({Caput mulieris vir. caput viri christus. christi vero deus.{)"
text = re.sub(emendation, "\g<1>", string)
  1. Run pylint on the file.

Current behavior

W: 4, 0: Anomalous backslash in string: '\g'. String constant might be missing an r prefix. (anomalous-backslash-in-string)

Expected behavior

No warning here, because regex group syntax works with one backslash even without being in a raw string.

pylint --version output

No config file found, using default configuration
pylint 1.6.5,
astroid 1.4.9
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)]

Most helpful comment

I disagree and think that this shouldn't produce a warning for the same reason that "\n" in a non-raw string doesn't produce a warning. This isn't so much a weird case that happens to work with an anomalous backslash but a built-in Python feature where a single backslash followed by a specific character has a special meaning and special behavior when creating strings.

But it's also not very important either way, so do what you will.

All 3 comments

_No warning here, because regex group syntax works with one backslash even without being in a raw string._
To be frank, most of Pylint checks are emitted even if code works....

I'd be inclined to close it as "will not fix". Warning tells the truth and suggests a correct fix (using an r prefix). Backslash has a meaning in string literals, and this is an anomalous backslash in string literal. The fact that it does not cause a malfunction in that exact case is not that important.

I disagree and think that this shouldn't produce a warning for the same reason that "\n" in a non-raw string doesn't produce a warning. This isn't so much a weird case that happens to work with an anomalous backslash but a built-in Python feature where a single backslash followed by a specific character has a special meaning and special behavior when creating strings.

But it's also not very important either way, so do what you will.

Yeah, detecting when the string is used in a regex might be too much for this check. I agree with @rogalski over here

Was this page helpful?
0 / 5 - 0 ratings