I am using a re.sub callback to replace substrings with random values, but I would like the random values to be the same across different strings. Since the re.sub callback does
You could create a closure.
def evaluator(mappings):
def f(match):
return str(eval(match.group(0)[2:-1], mappings))
return f
evaluate = evaluator({'A': 1, 'B': 2})
Since f
is just a single statement, you could simply use lambda
:
def evaluator(mappings):
return lambda match: str(eval(match.group(0)[2:-1], mappings))