[Tutor] Not understanding this code example. Help, please.

Eduardo Vieira eduardo.susan at gmail.com
Sun Feb 14 02:02:45 CET 2010


On Sat, Feb 13, 2010 at 7:59 AM, Kent Johnson <kent37 at tds.net> wrote:
> On Fri, Feb 12, 2010 at 11:49 PM, Eduardo Vieira
> <eduardo.susan at gmail.com> wrote:
>> Hello! I was reading the latest version of Mark Pilgrim's "Dive into
>> Python" and am confused with these example about the pluralization
>> rules. See http://diveintopython3.org/examples/plural3.py and
>> http://diveintopython3.org/generators.html#a-list-of-patterns
>> Here is part of the code:
>> import re
>>
>> def build_match_and_apply_functions(pattern, search, replace):
>>    def matches_rule(word):
>>        return re.search(pattern, word)
>>    def apply_rule(word):
>>        return re.sub(search, replace, word)
>>    return (matches_rule, apply_rule)
>>
>> patterns = \
>>  (
>>    ('[sxz]$',           '$',  'es'),
>>    ('[^aeioudgkprt]h$', '$',  'es'),
>>    ('(qu|[^aeiou])y$',  'y$', 'ies'),
>>    ('$',                '$',  's')
>>  )
>> 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)
>>
>> this example works on IDLE: print plural("baby")
>> My question is "baby" assigned to "word" in the inner function? It's a
>> little mind bending for me...
>
> It is a little mind bending when you first start seeing functions used
> as first-class objects. In Python functions are values that can be
> passed as arguments, returned, and assigned just like any other value.
> This can simplify a lot of problems.
>
> In this case I think the use of functions makes the code needlessly
> complicated. Without build_match_and_apply_functions() and the rules
> list it would look like this:
>
> def plural(noun):
>   for (pattern, search, replace) in patterns:
>       if re.search(pattern, noun):
>           return re.replace(search, replace, noun)
>
> which is not much longer that the original plural(), doesn't require
> all the helper machinery and IMO is easier to understand.
>
> Kent
>

Thanks for the input. Yes, there are simple ways to do it. If I recall
the author shows 3 or 4 different ways of doing this, each showing
some of python's features. This one was to introduce the concept of
closures.

Cheers,

Eduardo


More information about the Tutor mailing list