Reputation: 199
I'm trying to get a better understanding of how lambda functions and regex matches work in Python. For this purpose I'm replacing a lambda with a named function.
Even though I've found a way to make it work, I'm not able to understand why it works.
The lambda/regex I'm working on are the one mentioned in the following posts:
How to replace multiple substrings of a string?
Python - Replace regular expression match with a matching pair value
This is the main piece of code:
import re
# define desired replacements here
rep = {"condition1": "", "condition2": "text"}
text = "(condition1) and --condition2--"
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.items())
pattern = re.compile("|".join(rep.keys()))
output = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
print(output)
>>> '() and --text--'
If I replace the lambda function with:
def replace_conditions(match, rep):
return rep[re.escape(match.group(0))]
output = pattern.sub(replace_conditions(m, rep), text)
I get the following exception:
NameError: name 'm' is not defined
And I'm able to make it work only using this syntax:
def replace_conditions(match, rep=rep):
return rep[re.escape(match.group(0))]
output = pattern.sub(replace_conditions, line)
NOTE: I had to pre-assign a value to the second argument "rep" and use the function's name without actually calling it.
I can't understand why the match returned by the regex expression is properly passed on to the function if called with no arguments, while it's not passed to its first argument when called with the usual syntax.
Upvotes: 1
Views: 1699
Reputation: 39227
I can't understand why the match returned by the regex expression is properly passed on to the function if called with no arguments
That's not what's happening. pattern.sub(replace_conditions, line)
doesn't call the replace_conditions
function, it just passes it on.
From the docs for:
re.sub(pattern, repl, string, count=0, flags=0)
which is the same as:
pattern.sub(repl, string)
If
repl
is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
Upvotes: 1