Search code examples
pythonregexflake8

How to satisfy "[FLAKE8 W605] invalid escape sequence '\.'" and string format in the mean time?


I have an issue in python. My original regex expression is:

f"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"

(method_name is a local variable) and I got a lint warning:

"[FLAKE8 W605] invalid escape sequence '\.'Arc(W605)" 

Which looks like recommends me to use r as the regex prefix. But if I do:

r"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"

The {method_name} becomes the string type rather than a passed in variable.

Does anyone have an idea how to solve this dilemma?


Solution

  • Pass in the expression:

    r"regex(metrics_api_failure\.prod\.[\w_]+\." + method_name + r"\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
    

    Essentially, use Python string concatenation to accomplish the same thing that you were doing with the brackets. Then, r"" type string escaping should work.

    or use a raw format string:

    rf"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"