Thursday, May 10, 2012

Python.-Closures.Functions that build other functions

I'm studying Dive Into Python 3 and I'm pretty much in love with it.

From Chapter 6. Closures and Generators.
Guess what? Functions are just other kind of objects in Python!

The technique of using the values of outside parameters within a dynamic function is called closures
import re

def build_match_and_apply_functions(pattern,search,replace):
    builds dynamically a tuple containing two functions (matches_rule,apply_rule) for each tuple (pattern,search,replace) received
    the constants patter,search and replaced get substituted by the actual parameters passed to the function accordingly
    def matches_rule(word):
    def apply_rule(word):
        return re.sub(search,replace,word)
    return (matches_rule,apply_rule)

patterns = \
for each of these patterns two functions will be built a match_rule  and an apply_rule functions

this is called a list comprehension in Python terms
in this case we have as a result, a list containing tuples of match_rule and apply_rule functions
rules = [build_match_and_apply_functions(pattern,search,replace)
         for (pattern, search,replace) in patterns]


def plural(noun):
    for matches_rule, apply_rule in rules:
        if matches_rule(noun):
            return apply_rule(noun)
nouns = ["sufix","trash","lady","cat","math","boy","day",'pita','vacancy']
for noun in nouns:

I'm still in the process of assimilation, and this is pretty cool stuff.

No comments:

Post a Comment