how do you use a closure in a class

E

erinhouston

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?
 
P

Paul McGuire

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}
 
C

Cameron Laird

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.
 
T

Terry Reedy

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
 
P

Paul McGuire

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
 
E

erinhouston

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.
 
E

erinhouston

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.
 
P

Paul McGuire

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
 
E

erinhouston

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.
 
T

Terry Reedy

Paul McGuire said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top