Python Closures
June 12, 2010
I wanted to do a regex based search and replace in python, but I wanted something else to be passed into the match function (the current project name), so that I could include it in the replacement text. A quick post on stackoverflow gave me the answer - create a closure and have a function return a function.
The regex replace function is returned from the _replace function here:
def _replace(pProjectName, pType): """ This function creates and returns the match function for the regex in wamtext """ def f(matchobj): lMatch = matchobj.group(1) return "<a href='/%s/%s/%s/' title='Go to %s %s'>%s</a>" % (pType.lower(), pProjectName, lMatch, pType, lMatch, lMatch) return f
This is called when doing the replace:
lReturn = re.sub(r'\[txn:(\w+)]', _replace(pCurrentProjectName, "Class"), lReturn) lReturn = re.sub(r'\[class:(\w+)]', _replace(pCurrentProjectName, "Class"), lReturn) lReturn = re.sub(r'\[usecase:([ \w]+)]', _replace(pCurrentProjectName, "UseCase"), lReturn)