Home > Software engineering >  Python: using def to define an anonymous function for use in re.sub
Python: using def to define an anonymous function for use in re.sub

Time:05-08

I haven't been able to find an answer to whether this is legal or not. It's a function to find and replace in a string, all "variables" (which are words that start with v_). I can't use a lambda because I need more than one line for the replaceor function due to the necessity of the "if" clause.

def fillin(template, dictionary):
    result = re.sub(r'v_([a-z_] )', def(match):
        variable = match.group(1)
        if not variable in dictionary:
            return match # don't replace nuthin'                                                   
        return dictionary[variable],
        Scene )
    return result

It gets all strings that start with a v_ in this text, then looks at the remainder of the string to get a "variable name", look that up in a dictionary and replace the string with the looked up value.

I can't use a lambda because I need an "if key in dictionary" clause in there to prevent an lookup error in the dictionary.

Is there no way to use def for anonymous functions?

CodePudding user response:

I think this lambda will work for you.

lambda match: match if not match.group(1) in dictionary else dictionary[match.group(1)]

CodePudding user response:

You can use a lambda, and still keep it short if you use dictionary.get(x.group(1), x.group()):

re.sub(r'v_([a-z_] )', lambda x: dictionary.get(x.group(1),x.group()), text)

See the Python demo:

import re
text = "aaa v_abc v_def"
dictionary = { 'abc':'yes' }
print( re.sub(r'v_([a-z_] )', lambda x: dictionary.get(x.group(1),x.group()), text) )
# => aaa yes v_def

CodePudding user response:

You define your function Before the place you are to call `re.sub', and just pass the function as a normal parameter. The "def" declaration gives the function a name - that references the function the same way an inplace "lambda" expression does.

def replacer(match):
   variable = match.group(1)
   if not variable in dictionary:
       return match # don't replace nuthin'                                                   
   return dictionary[variable]

def fillin(template, dictionary):
    result = re.sub(r'v_([a-z_] )', replacer, Scene)
    return result

  • Related