By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 1,932 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

how do you use a closure in a class

P: n/a
I have several functions that are almost the same in one class I would
like to use a closure to get rid of the extra code how would I do this?

Jul 18 '05 #1
Share this Question
Share on Google+
10 Replies


P: n/a
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}

Jul 18 '05 #2

P: n/a
In article <11**********************@l41g2000cwc.googlegroups .com>,
Paul McGuire <pt***@austin.rr.com> wrote:
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}


Help me. While I recognize you're looking to construct a
pedagogically-meaningful example, all that typing makes me
wonder what lesson we're teaching. To me, it's more in the
spirit of python to have a

if c in "aeiou":
...
elif c in "bcdfghjklmnpqrstvwxz":
...
elif c == "y":
...

in there somewhere. What am I missing about your dictionary
construction?

It's hard for me to type the same variable reference repeatedly.
Jul 18 '05 #3

P: n/a

<er*********@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
I have several functions that are almost the same in one class I would
like to use a closure to get rid of the extra code how would I do this?


A more specific example might get a more to the point solution ;-)

TJR

Jul 18 '05 #4

P: n/a
Well, despite my parenthetical disclaimer, my attempted point was that
the OP wanted to avoid replicating several functions that were mostly
the same. I think Python's idiom of using a function to create and
return callables is a comparable feature to using anonymous closures.
Unfortunately, I guess the verbosity of the tallyFn calls was too much
of a distraction. The cut-and-paste alternative (which the OP was
trying to avoid) would be:

def tallyConsonant():
.....tally["consonant] += 1

def tallyVowel():
.....tally["vowel"] += 1

def tallyNotSure():
.....tally["notsure"] += 1

def tallyOther():
.....tally["other"] += 1

I was hoping to offer an example of the Pythonic
function-returns-a-callable idiom, instead of having this discussion
spiral down into another "what we really need are brace-enclosed
anonymous enclosures" futility.

-- Paul

Jul 18 '05 #5

P: n/a
What I wanted it to know how to. Take a function like.
Note replace ... with spaces.
def makeAddr(tAdd):
.....def add(tNum):
.........return tNum + tAdd
.....return add

In a class so I make several functions that do the same thing but on
diffrent objects.
I ended up writing a base function and just wrapping it for all the
cases. If there is a way to use this type of function to create class
functions I would like to know how.

Jul 18 '05 #6

P: n/a
Also note I can't read or type is seems.

what I want to know is how to take a function like.

I realley need to fininsh my coke before I try to think.

Jul 18 '05 #7

P: n/a
See the following.
-- Paul

class X(object):
.....pass

def makeAddr(tAdd):
.....def add(self, tNum):
.........return tNum + tAdd
.....return add

# add methods to class X
X.add1 = makeAddr(1)
X.add100 = makeAddr(100)

# create an X object
x = X()

# invoke new methods
print x.add1( 50 )
print x.add100( 50 )

Prints:
51
150

Jul 18 '05 #8

P: n/a
Thanks I will try that.

Jul 18 '05 #9

P: n/a
Thanks that made it work. If I did it that way I think the other
programmers on my team would kill me so I will stick with wrapping the
function over and over again.

Jul 18 '05 #10

P: n/a

"Paul McGuire" <pt***@austin.rr.com> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com...
See the following.
-- Paul

class X(object):
....pass

def makeAddr(tAdd):
....def add(self, tNum):
........return tNum + tAdd
....return add

# add methods to class X
X.add1 = makeAddr(1)
X.add100 = makeAddr(100)


You or others might find this rearrangement stylistically preferable:
define makeAddr first, then

class X(object):
add1 = makeAddr(1)
add100 = makeAddr(100)
....

Terry J. Reedy

Jul 18 '05 #11

This discussion thread is closed

Replies have been disabled for this discussion.