Passing info to function used in re.sub
MRAB
python at mrabarnett.plus.com
Sun Sep 3 13:13:10 EDT 2023
On 2023-09-03 17:10, Jan Erik Moström via Python-list wrote:
> I'm looking for some advice for how to write this in a clean way
>
> I want to replace some text using a regex-pattern, but before creating replacement text I need to some file checking/copying etc. My code right now look something like this:
>
> def fix_stuff(m):
> # Do various things that involves for info
> # that what's available in m
> replacement_text = m.group(1) + global_var1 + global_var2
> return replacement_text
>
> and the call comes here
>
> global_var1 = "bla bla"
> global_var2 = "pff"
>
> new_text = re.sub(im_pattern,fix_stuff,md_text)
>
>
> The "problem" is that I've currently written some code that works but it uses global variables ... and I don't like global variables. I assume there is a better way to write this, but how?
>
You could use pass an anonymous function (a lambda) to re.sub:
def fix_stuff(m, var1, var2):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + var1 + var2
return replacement_text
global_var1 = "bla bla"
global_var2 = "pff"
new_text = re.sub(im_pattern, lambda m, var1=global_var1,
var2=global_var2: fix_stuff(m, var1, var2), md_text)
Or, if you prefer a named function, define one just before the re.sub:
def fix_stuff(m, var1, var2):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + var1 + var2
return replacement_text
global_var1 = "bla bla"
global_var2 = "pff"
def fix_it(m, var1=global_var1, var2=global_var2):
return fix_stuff(m, var1, var2)
new_text = re.sub(im_pattern, fix_it, md_text)
More information about the Python-list
mailing list