[py-usr] flake8 gives me a W605 but Python don't

MRAB python at mrabarnett.plus.com
Sat Sep 10 15:37:23 EDT 2022


On 2022-09-10 19:46, c.buhtz at posteo.jp wrote:
> Hello,
> 
> My `flake8` gives me a "W605 invalid escape sequence" [1] warning for
> this piece of example code.
> 
>      import re
>      
>      def foobar():
>          rex = re.compile('Version: \d+.\d+.\d+.*', re.MULTILINE)
>      
>          for match in rex.findall(' Version: 1.2.3 '):
>              print(match)
>      
>      
>      if __name__ == '__main__':
>          foobar()
> 
> But running this with Python 3.9.2 makes no problem. Python doesn't
> give me a `SyntaxWarning` or anything else. Python doesn't give me an
> error or warning. Only `flymake8` gives me this error.
> 
> I do understand what is wrong with the pattern string in `compile()`.
> There should be a `r''` or the regex-escape characters should be
> escaped them selfs (e.g. `'Version: \\d'`).
> 
> But my question is about why Python doesn't give me an error about it
> and why does it work. The pattern matches. Shouldn't there be an error
> or something? Does Python identify this string as an r-String by itself?
> 
> [1] -- <https://www.flake8rules.com/rules/W605.html>

Historically, invalid escapes such as '\d' have always been treated as 
'\\d', but that is, and always, bad idea; it's better to treat them as 
an error (or reserved for future use).

At some point, in some future version of Python, they should become an 
error, but there's always a chance that some code out there could break, 
so there's a long period of deprecation first. How long? Who knows!

Just take note of the warning, and don't write bad escapes.


More information about the Python-list mailing list