how do you use a closure in a class

Paul McGuire ptmcg at austin.rr.com
Tue Mar 29 16:10:51 EST 2005


Well, I'm not sure "closure" is the Pythonic way.  But in Python, you
can use functions to dynamically create other functions.  Here's an
example of this feature (although there are far simpler ways to do
this), tallying vowels and consonants in an input string by calling a
function looked up in a dictionary.  Note that tallyFn creates a
temporary function that uses the 'key' argument passed into tallyFn,
and then returns the temporary function.  Perhaps this idiom can serve
in place of your concept of closures for small anonymous functions.

-- Paul

(replace the leading .'s with spaces - I'm posting with Google Groups):

# global tally structure
tally = {}
tally["consonant"] = 0
tally["vowel"] = 0
tally["not sure"] = 0
tally["none"] = 0

# function to construct other functions (instead of closures)
def tallyFn( key ):
....def addToTally():
........tally[key] = tally[key] + 1
....return addToTally

# create dict of functions
functions = {}
functions["a"] = tallyFn("vowel")
functions["b"] = tallyFn("consonant")
functions["c"] = tallyFn("consonant")
functions["d"] = tallyFn("consonant")
functions["e"] = tallyFn("vowel")
functions["f"] = tallyFn("consonant")
functions["g"] = tallyFn("consonant")
functions["h"] = tallyFn("consonant")
functions["i"] = tallyFn("vowel")
functions["j"] = tallyFn("consonant")
functions["k"] = tallyFn("consonant")
functions["l"] = tallyFn("consonant")
functions["m"] = tallyFn("consonant")
functions["n"] = tallyFn("consonant")
functions["o"] = tallyFn("vowel")
functions["p"] = tallyFn("consonant")
functions["q"] = tallyFn("consonant")
functions["r"] = tallyFn("consonant")
functions["s"] = tallyFn("consonant")
functions["t"] = tallyFn("consonant")
functions["u"] = tallyFn("vowel")
functions["v"] = tallyFn("consonant")
functions["w"] = tallyFn("consonant")
functions["x"] = tallyFn("consonant")
functions["y"] = tallyFn("not sure")
functions["z"] = tallyFn("consonant")
functions[" "] = tallyFn("none")
functions["."] = tallyFn("none")

testdata = """
The quick brown fox jumps over the lazy dog.
Now is the time for all good men to come to.
Many hands make light work heavy.
"""

for line in testdata.split("\n"):
....for c in line.lower():
........fn = functions[c]
........fn()

print tally

Gives:
{'none': 26, 'consonant': 59, 'not sure': 3, 'vowel': 33}




More information about the Python-list mailing list