1

Hi I am writing a lot of function with the following form:

def is_match_a(doc):
    pattern = # spaCy patterns
    matcher = Matcher(nlp.vocab)
    matcher.add("match_a", [pattern])
    matches = matcher(doc)
    if matches:
        return True

I want to write a function that generate these function from a given pattern and name. I am thinking something like:

def generate_matcher(pattern, name):
    func = some code
    return func

so that ultimately, I can do something the following

is_match_a = generate_matcher(pattern_a, name_a)
is_match_b = generate_matcher(pattern_b, name_b)
if is_match_a(doc):
    # do something
elif is_match_b(doc):
    # do something else

I am new to python and I can not wrap my head around how to go about this. Is this where you use decorator?

1
  • In is_match_a() you could just return matches as opposed to checking if it is True
    – Xiddoc
    Commented Sep 30, 2021 at 18:49

1 Answer 1

4

Define a nested function that uses the pattern and name parameters of the main function.

def generate_matcher(pattern, name):
    def is_match(doc):
        matcher = Matcher(nlp.vocab)
        matcher.add(name, [pattern])
        matches = matcher(doc)
        if matches:
            return True

    return is_match
2
  • Thanks! Is this a problem that will merit from using decorator?
    – Imrul Huda
    Commented Sep 30, 2021 at 19:31
  • 1
    Not really. A decorator is used when you want to add code around some other function, not just to provide parameters to it.
    – Barmar
    Commented Sep 30, 2021 at 19:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.