rule-engine
rule-engine copied to clipboard
Python 3.12 and escaping regex
Hello,
I've updated my environment to Python 3.12, from Python 3.11 and now see issues when escaping a regex string and pass it when instantiating a Rule object. It seems that this is due to a change in Python 3.12 showing a SyntaxWarning instead of a DeprecationWarning for invalid string literals.
It seems that the answer to resolve this is to use raw strings.
I'm able to reproduce the warning with the cod below:
import re
import rule_engine
def test():
"""
Create a rule that checks if the username matches 'joe.blogs' exactly.
"""
# This regex is usually created dynamically of rules that are stored in the database.
value = re.escape("joe.blogs")
# Check if the some_attribute key in the dictionary matches 'joe.blogs' exactly
rule = rule_engine.Rule(rf'some_attribute =~ "^{value}$"')
Whilst in this case it would be possible to not use regex, the methods I've built around the library allow users to configure multiple rules, with many combinations of comparators, case-sensitivity etc, so using regex made this much simpler to achieve.
If I do not use re.escape
I no longer see the warning, however the .
is not longer escaped in the username, so something like joe1blogs
would match, which is not the desired behaviour.
Please let me know if you need any further details.
Best, Ryan