473,385 Members | 1,769 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

how do you use a closure in a class

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
10 2316
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
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

<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
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
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
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
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
Thanks I will try that.

Jul 18 '05 #9
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

"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: John J. Lee | last post by:
I'm trying define a class to act as a Mock "handler" object for testing urllib2.OpenerDirector. OpenerDirector (actually, my copy of it) does dir(handler.__class__) to find out what methods a...
27
by: Ted Lilley | last post by:
What I want to do is pre-load functions with arguments by iterating through a list like so: >>>class myclass: .... pass >>>def func(self, arg): .... print arg >>>mylist = >>>for item...
1
by: Victor Ng | last post by:
Is there a way to preserve the argspec of a function after wrapping it in a closure? I'm looking for a general way to say "wrap function F in a closure", such that inspect.getargspec on the...
9
by: Mikito Harakiri | last post by:
Transitive closure (TC) of a graph is with TransClosedEdges (tail, head) as ( select tail, head from Edges union all select e.tail, ee.head from Edges e, TransClosedEdges ee where e.head =...
7
by: Csaba Gabor | last post by:
I feel like it's the twilight zone here as several seemingly trivial questions are bugging me. The first of the following three lines is a syntax error, while the last one is the only one that...
9
by: User1014 | last post by:
I'm a javascript noob and have a question concerning some code I've come across that I'm trying to understand. Here is a snippet of the relevant section: (snip) var closure = this; var xhr =...
0
by: Gerard Brunick | last post by:
Consider: ### Function closure example def outer(s): .... def inner(): .... print s .... return inner .... 5
11
by: Huayang Xia | last post by:
What will the following piece of code print? (10 or 15) def testClosure(maxIndex) : def closureTest(): return maxIndex maxIndex += 5 return closureTest()
4
by: LAN MIND | last post by:
?
2
by: ssecorp | last post by:
A method on a class: def printSelf(self): def printReviews(): for review in self.reviews: review.printSelf() print "Idnbr: ", self.idnumber, "Reviews: ", printReviews() I don't have to pass...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.