Thursday, December 27, 2007

Obviously I'm not Even an Intermediate Level Python Programmer

While a thread on regex performance revealed how much I've forgotten (or never knew) even though I started coding in Python (1.5.x) back in 1999. My confusion didn't have really anything to do with regexes but the two different approaches, one which was more peculiar to my only-coding-in-Ruby-recently brain:

Class Approach
import re
class Searcher(object):
def __init__(self, rex):
self.crex = re.compile(rex)
def __call__(self, txt):
return self.crex.search(txt)

s = Searcher("dog")
print s("dog").string

After I remembered what the __call__ was used for (which I actually like) and got used to the __'s (which I don't like) and I've never liked the self's in Python method arguments -- this made sense.

Function Returning a Function
import re
def searcher(rex):
crex = re.compile(rex)
def _(txt):
return crex.search(txt)
return _
s = searcher("dog")
print s("dog").string


At first this didn't make much sense and I got tricked by the underscore (thinking it was some sort of Perl-like special function name or something, it isn't though!). Wny would I call a function returning another function that I would use over and over again. Why would you do that? What is interesting though is if that s("dog")("dog") also produces identical results although I have no idea why (except that the first nested function within a function always executes the second parameter).

No comments: