Improve SafeRe code readability
function isSafePattern was never used as boolean function, its only useful behaviour being raising exception on bad regexp, so it's renamed and reused accordingly
This commit is contained in:
parent
30db5a4652
commit
5fadd5f9bd
2 changed files with 8 additions and 9 deletions
|
@ -7,7 +7,8 @@ class UnsafePatternError(Exception):
|
|||
cached_patterns = {}
|
||||
|
||||
|
||||
def isSafePattern(pattern):
|
||||
def guard(pattern):
|
||||
'''Checks if pattern is safe and raises exception if it isn't'''
|
||||
if len(pattern) > 255:
|
||||
raise UnsafePatternError("Pattern too long: %s characters in %s" % (len(pattern), pattern))
|
||||
|
||||
|
@ -20,14 +21,13 @@ def isSafePattern(pattern):
|
|||
if len(repetitions1) + len(repetitions2) >= 10:
|
||||
raise UnsafePatternError("More than 10 repetitions in %s" % pattern)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def match(pattern, *args, **kwargs):
|
||||
'''Guard for safety, compile, cache and match regexp'''
|
||||
cached_pattern = cached_patterns.get(pattern)
|
||||
if cached_pattern:
|
||||
return cached_pattern.match(*args, **kwargs)
|
||||
else:
|
||||
if isSafePattern(pattern):
|
||||
cached_patterns[pattern] = re.compile(pattern)
|
||||
return cached_patterns[pattern].match(*args, **kwargs)
|
||||
guard(pattern)
|
||||
cached_patterns[pattern] = re.compile(pattern)
|
||||
return cached_patterns[pattern].match(*args, **kwargs)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue