Snake_Plissken
Snake_Plissken

Reputation: 400

Pass a method as a function parameter

Is it possible to pass a method as a function parameter?

In learning regular expressions and how to use them, I decided to try and create a function I can just repeatedly call with the different regular expression methods that are used:

    def finder (regex, query, method):
        compiled = re.compile(regex)
        if compiled.method(query) is True:
            print "We have some sort of match!"
        else:
            print "We do not have a match..."

When I try it out, I get an atrribute error: '_sre.SRE_pattern' has no attribute 'method' even though I pass "search" as the 3rd parameter, which should be callable on compiled. What am I doing incorrectly or not completely understanding here?

Upvotes: 2

Views: 137

Answers (1)

unutbu
unutbu

Reputation: 879591

Pass method as a string, and use getattr:

def finder (regex, query, method):
    compiled = re.compile(regex)
    if getattr(compiled, method)(query):
        print "We have some sort of match!"
    else:
        print "We do not have a match..."

finder(regex, query, "search")

Also, use

if condition

instead of

if condition is True

because when compiled.method(query) finds a match, it returns a match object, not True.

Upvotes: 3

Related Questions