0

I have a method that as part of its work, calls re.sub with the replacement value supplied as a function. This function is defined within this greater function.

The problem is the this inner function that is passed as a parameter to re.sub is not able to access variables defined in the outer function. How can I make the outer scope available?

The code is below with work sensitive portions removed. The important parts are the callback function _unsub_link_replacement and the var unsub_link which I would like the callback function to have access to, which it does not.

The one caveat is that I must use regular expressions for this.

@classmethod
def process_unsub_link(cls, html_content):
    protocol = "http:" # TODO - this needs to be derived
    host = "localhost:8080" # TODO - this needs to be derived
    ns = urllib.quote("fake_namespace") # TODO - this needs to be derived
    unsub_link_section = "/callback/unsub/?ns={}".format(ns)
    unsub_link = "{}//{}{}".format(protocol, host, unsub_link_section)

    def _unsub_link_replacement(match):
        if len(match.groups()) == 2: # Success case
            value = match.groups(1)
                if value not in unsub_link:
                    do_unspecified_things()

    pattern = "(\*\|\s*UNSUB:([^\s\|]*)\s*\|\*)"
    content = re.sub(pattern, _unsub_link_replacement, html_content)
    return content
Laurel
  • 5,965
  • 14
  • 31
  • 57
user3835102
  • 11
  • 1
  • 1
  • 3

1 Answers1

-1

I think this answer hits on what you're looking for.

I think the simple solution is to make unsub_link a global variable, which seems hackish but would let your callback function have access to it.

Community
  • 1
  • 1
Jonathan Holmes
  • 438
  • 2
  • 12