Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

functions which take functions

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


kiuhnm03.4t.yahoo.it at mail

Apr 9, 2012, 11:57 AM

Post #1 of 17 (732 views)
Permalink
functions which take functions

Do you have some real or realistic (but easy and self-contained)
examples when you had to define a (multi-statement) function and pass it
to another function?
Thank you.

Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list


tjreedy at udel

Apr 9, 2012, 1:34 PM

Post #2 of 17 (705 views)
Permalink
Re: functions which take functions [In reply to]

On 4/9/2012 2:57 PM, Kiuhnm wrote:
> Do you have some real or realistic (but easy and self-contained)
> examples when you had to define a (multi-statement) function and pass it
> to another function?

This is so common in Python that it is hardly worth sneezing about.

map(f, iterable)
filter(f, iterable)
functools.wraps(f, args)

---
Sometimes it is a bit hidden.

@deco
def f(): pass

is equivalent to

def f(): pass # replace with multiple statements
f = deco(f)

In fact, one reason for moving the wrapper above the def line is that
function bodies can be arbitrarily large, moving the explicit call
arbitrarily far away.

---
class C():
def test(self): print(self, '.test called')

c = C()
c.test()
import types
types.MethodType(c.__class__.test, c)()
# This *is* the internal implementation of c.test

#prints
<__main__.C object at 0x000000000363E278> .test called
<__main__.C object at 0x000000000363E278> .test called

----
In numerical analysis, functions that numerically integrate,
differentiate, regress, fit, or plot functions take functions as arguments.

---
The most common, so common you do not notice it, is passing functions to
other functions via the global namespace that is the hidden argument to
all functions. (Every function has a readonly .__globals__ attribute
that is used to resolve global accesses.)

def g(): pass
def h(): pass
def j(a): return g(h(a))

Be glad you do not have to *always* do something like

def j(a, funcs): return funcs.g(funcs.h(a))
print(j(a, locals()))

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


emile at fenx

Apr 9, 2012, 2:20 PM

Post #3 of 17 (706 views)
Permalink
Re: functions which take functions [In reply to]

On 4/9/2012 11:57 AM Kiuhnm said...
> Do you have some real or realistic

... yes

> (but easy and self-contained)

.... aah, no.

> examples when you had to define a (multi-statement) function and pass it
> to another function?

This weekend I added functionality to a subsystem that allows users to
write simple get functions stored in [funcname].py files in a specified
directory that are read, compliled, and stored in a dictionary to be
executed dynamically. So, when a properly crafted command is recieved
the corresponding function object is retrieved from the dictionary and
exectued.

... hang on ... ok -- here's a simple self contained example - HTH!

Emile

----

STACK=[]

def push(this):
STACK.append(int(this))

def plus(this):
tosa,tosb = STACK.pop(),STACK.pop()
push(tosa+tosb)

def minus(this):
tosa,tosb = STACK.pop(),STACK.pop()
push(tosa-tosb)

def times(this):
tosa,tosb = STACK.pop(),STACK.pop()
push(tosa*tosb)

def div(this):
tosa,tosb = STACK.pop(),STACK.pop()
push(tosb/tosa)

def equals(this):
return STACK.pop()

funcs = { "+" : plus,
"-" : minus,
"*" : times,
"/" : div,
"=" : equals
}


def calculate (text):
for part in text.split():
retval = funcs.get(part,push)(part)
return retval


assert calculate ("4 3 + =") == 7
assert calculate ("4 3 * =") == 12
assert calculate ("12 3 / =") == 4
assert calculate ("1 2 3 4 + + + =") == 10

--
http://mail.python.org/mailman/listinfo/python-list


ulrich.eckhardt at dominolaser

Apr 10, 2012, 5:29 AM

Post #4 of 17 (704 views)
Permalink
Re: functions which take functions [In reply to]

Am 09.04.2012 20:57, schrieb Kiuhnm:
> Do you have some real or realistic (but easy and self-contained)
> examples when you had to define a (multi-statement) function and pass it
> to another function?

Take a look at decorators, they not only take non-trivial functions but
also return them. That said, I wonder what your intention behind this
question is...

:)

Uli

--
http://mail.python.org/mailman/listinfo/python-list


kiuhnm03.4t.yahoo.it at mail

Apr 10, 2012, 6:36 AM

Post #5 of 17 (703 views)
Permalink
Re: functions which take functions [In reply to]

On 4/10/2012 14:29, Ulrich Eckhardt wrote:
> Am 09.04.2012 20:57, schrieb Kiuhnm:
>> Do you have some real or realistic (but easy and self-contained)
>> examples when you had to define a (multi-statement) function and pass it
>> to another function?
>
> Take a look at decorators, they not only take non-trivial functions but
> also return them. That said, I wonder what your intention behind this
> question is...
>
> :)

That won't do. A good example is when you pass a function to re.sub, for
instance.

Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list


hoogendoorn.eelco at gmail

Apr 10, 2012, 2:43 PM

Post #6 of 17 (703 views)
Permalink
Re: functions which take functions [In reply to]

On Apr 10, 3:36 am, Kiuhnm <kiuhnm03.4t.yahoo.it> wrote:
> On 4/10/2012 14:29, Ulrich Eckhardt wrote:
>
> > Am 09.04.2012 20:57, schrieb Kiuhnm:
> >> Do you have some real or realistic (but easy and self-contained)
> >> examples when you had to define a (multi-statement) function and pass it
> >> to another function?
>
> > Take a look at decorators, they not only take non-trivial functions but
> > also return them. That said, I wonder what your intention behind this
> > question is...
>
> > :)
>
> That won't do. A good example is when you pass a function to re.sub, for
> instance.
>
> Kiuhnm

Wont do for what? Seems like a perfect example of function-passing to
me.

If you have such a precise notion of what it is you are looking for,
why even ask?
--
http://mail.python.org/mailman/listinfo/python-list


rosuav at gmail

Apr 10, 2012, 3:18 PM

Post #7 of 17 (703 views)
Permalink
Re: functions which take functions [In reply to]

On Tue, Apr 10, 2012 at 11:36 PM, Kiuhnm
<kiuhnm03.4t.yahoo.it [at] mail> wrote:
> On 4/10/2012 14:29, Ulrich Eckhardt wrote:
>>
>> Am 09.04.2012 20:57, schrieb Kiuhnm:
>>>
>>> Do you have some real or realistic (but easy and self-contained)
>>> examples when you had to define a (multi-statement) function and pass it
>>> to another function?
>>
>>
>> Take a look at decorators, they not only take non-trivial functions but
>> also return them. That said, I wonder what your intention behind this
>> question is...
>>
>
> That won't do. A good example is when you pass a function to re.sub, for
> instance.

The most common case of such a thing is a structure walking utility.
For instance, a linked-list walker could be written as:

def walk(tree,func):
node=tree.head
while node:
func(node.data)
node=tree.sibling

This could equally reasonably be written with yield, though I'm not
sure that it's possible to write a recursive generator as cleanly (eg
to walk a binary tree). Perhaps the new "yield from" syntax would be
good here, but I've never used it. In any case, it's a classic use of
passing a function-like as a parameter, even if there's another way to
do it.

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list


kiuhnm03.4t.yahoo.it at mail

Apr 11, 2012, 3:55 AM

Post #8 of 17 (703 views)
Permalink
Re: functions which take functions [In reply to]

On 4/10/2012 23:43, Eelco wrote:
> On Apr 10, 3:36 am, Kiuhnm<kiuhnm03.4t.yahoo.it> wrote:
>> On 4/10/2012 14:29, Ulrich Eckhardt wrote:
>>
>>> Am 09.04.2012 20:57, schrieb Kiuhnm:
>>>> Do you have some real or realistic (but easy and self-contained)
>>>> examples when you had to define a (multi-statement) function and pass it
>>>> to another function?
>>
>>> Take a look at decorators, they not only take non-trivial functions but
>>> also return them. That said, I wonder what your intention behind this
>>> question is...
>>
>>> :)
>>
>> That won't do. A good example is when you pass a function to re.sub, for
>> instance.
>>
>> Kiuhnm
>
> Wont do for what? Seems like a perfect example of function-passing to
> me.

That's more an example of function transformation.

> If you have such a precise notion of what it is you are looking for,
> why even ask?

As I said, I need real-life examples. Enough with prime numbers and
recursive qsort...

Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list


d at davea

Apr 11, 2012, 4:18 AM

Post #9 of 17 (704 views)
Permalink
Re: functions which take functions [In reply to]

On 04/11/2012 06:55 AM, Kiuhnm wrote:
> On 4/10/2012 23:43, Eelco wrote:
>> On Apr 10, 3:36 am, Kiuhnm<kiuhnm03.4t.yahoo.it> wrote:
>>> On 4/10/2012 14:29, Ulrich Eckhardt wrote:
>>>
>>>> Am 09.04.2012 20:57, schrieb Kiuhnm:
>>>>> Do you have some real or realistic (but easy and self-contained)
>>>>> examples when you had to define a (multi-statement) function and
>>>>> pass it
>>>>> to another function?
>>>
>>>> Take a look at decorators, they not only take non-trivial functions
>>>> but
>>>> also return them. That said, I wonder what your intention behind this
>>>> question is...
>>>
>>>> :)
>>>
>>> That won't do. A good example is when you pass a function to re.sub,
>>> for
>>> instance.
>>>
>>> Kiuhnm
>>
>> Wont do for what? Seems like a perfect example of function-passing to
>> me.
>
> That's more an example of function transformation.
>
>> If you have such a precise notion of what it is you are looking for,
>> why even ask?
>
> As I said, I need real-life examples. Enough with prime numbers and
> recursive qsort...
>
> Kiuhnm

How about any GUI application? Every gui interface I've seen makes you
register your callbacks as functions, by passing the function object
into some gui function specific to an event or class of events.

Then when the event fires, the function is actually called.

--

DaveA

--
http://mail.python.org/mailman/listinfo/python-list


antti.ylikoski at tkk

Apr 11, 2012, 7:01 AM

Post #10 of 17 (701 views)
Permalink
Re: functions which take functions [In reply to]

On 9.4.2012 21:57, Kiuhnm wrote:
> Do you have some real or realistic (but easy and self-contained)
> examples when you had to define a (multi-statement) function and pass it
> to another function?
> Thank you.
>
> Kiuhnm

A function to numerically integrate another function comes as follows:

------------------------------------------------------

# Adaptive Simpson's integral.
#
# AJY 03-28-2012 from the Wikipedia.

import math

def simpsonsRule(f,a,b):
c = (a+b) / 2.0
h3 = abs(b-a) / 6.0
return h3*(f(a) + 4.0*f(c) + f(b))

def recursiveASR(f,a,b,eps,whole):
"Recursive implementation of adaptive Simpson's rule."
c = (a+b) / 2.0
left = simpsonsRule(f,a,c)
right = simpsonsRule(f,c,b)
if abs(left + right - whole) <= 15*eps:
return left + right + (left + right - whole)/15.0
return recursiveASR(f,a,c,eps/2.0,left) + \
recursiveASR(f,c,b,eps/2.0,right)

def adaptiveSimpsonsRule(f,a,b,eps):
"Calculate integral of f from a to b with max error of eps."
return recursiveASR(f,a,b,eps,simpsonsRule(f,a,b))

def invx(x):
return 1.0 / x


print("Simpson integral : ", \
adaptiveSimpsonsRule(invx,1.0,2.0,.000000001))
print("Exact value ln(2): ", math.log(2.0))
print("Value of epsilon : ", .000000001)


------------------------------------------------------------


kind regards, Antti J Ylikoski
Helsinki, Finland, the EU
http://www.tkk.fi/~ajy/
http://www.tkk.fi/~ajy/diss.pdf
antti.ylikoski [at] gmail
--
http://mail.python.org/mailman/listinfo/python-list


python.list at tim

Apr 11, 2012, 11:45 AM

Post #11 of 17 (702 views)
Permalink
Re: functions which take functions [In reply to]

On 04/10/12 08:36, Kiuhnm wrote:
> On 4/10/2012 14:29, Ulrich Eckhardt wrote:
>> Am 09.04.2012 20:57, schrieb Kiuhnm:
> That won't do. A good example is when you pass a function to
> re.sub, for instance.

If that's a good example, then why not use it? I've used it on
multiple occasions to do lookups for replacements, math on the
match bits, or other more complex calculations.

-tkc


--
http://mail.python.org/mailman/listinfo/python-list


timr at probo

Apr 11, 2012, 11:07 PM

Post #12 of 17 (701 views)
Permalink
Re: functions which take functions [In reply to]

Kiuhnm <kiuhnm03.4t.yahoo.it> wrote:
>
>That won't do. A good example is when you pass a function to re.sub, for
>instance.

This is an odd request.

I often pass functions to functions in order to simulate a C switch
statement, such as in a language translator:

commands = {
'add': doAdd,
'subtract' : doSubtract,
'multiply' : doMultiply,
'divide' : doDivide
}

nextCommand = parseCommandLine( line )
invokeCommand( commands[NextCommand] )
--
Tim Roberts, timr [at] probo
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


kiuhnm03.4t.yahoo.it at mail

Apr 12, 2012, 8:48 AM

Post #13 of 17 (690 views)
Permalink
Re: functions which take functions [In reply to]

On 4/11/2012 16:01, Antti J Ylikoski wrote:
> On 9.4.2012 21:57, Kiuhnm wrote:
>> Do you have some real or realistic (but easy and self-contained)
>> examples when you had to define a (multi-statement) function and pass it
>> to another function?
>> Thank you.
>>
>> Kiuhnm
>
> A function to numerically integrate another function comes as follows:
[...]

Thank you.

Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list


kiuhnm03.4t.yahoo.it at mail

Apr 12, 2012, 8:58 AM

Post #14 of 17 (692 views)
Permalink
Re: functions which take functions [In reply to]

On 4/12/2012 8:07, Tim Roberts wrote:
> Kiuhnm<kiuhnm03.4t.yahoo.it> wrote:
>>
>> That won't do. A good example is when you pass a function to re.sub, for
>> instance.
>
> This is an odd request.

All shall be revealed :)

>
> I often pass functions to functions in order to simulate a C switch
> statement, such as in a language translator:
>
> commands = {
> 'add': doAdd,
> 'subtract' : doSubtract,
> 'multiply' : doMultiply,
> 'divide' : doDivide
> }
>
> nextCommand = parseCommandLine( line )
> invokeCommand( commands[NextCommand] )

I like that very much. Thank you.

Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list


jan.kuiken at quicknet

Apr 12, 2012, 10:29 AM

Post #15 of 17 (693 views)
Permalink
Re: functions which take functions [In reply to]

On 4/9/12 20:57 , Kiuhnm wrote:

> Do you have some real or realistic (but easy and self-contained)
> examples when you had to define a (multi-statement) function and pass it
> to another function?

I don't use it daily but the first argument of list.sort, i.e. the
compare function springs to mind.

Jan Kuiken


--
http://mail.python.org/mailman/listinfo/python-list


kiuhnm03.4t.yahoo.it at mail

Apr 12, 2012, 4:07 PM

Post #16 of 17 (689 views)
Permalink
Re: functions which take functions [In reply to]

On 4/12/2012 19:29, Jan Kuiken wrote:
> On 4/9/12 20:57 , Kiuhnm wrote:
>
>> Do you have some real or realistic (but easy and self-contained)
>> examples when you had to define a (multi-statement) function and pass it
>> to another function?
>
> I don't use it daily but the first argument of list.sort, i.e. the
> compare function springs to mind.

Yes, I guess there are times when a lambda is not enough and one needs
to define a real function.
Thanks.

Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list


antti.ylikoski at hut

Apr 13, 2012, 6:23 AM

Post #17 of 17 (690 views)
Permalink
Re: functions which take functions [In reply to]

12.4.2012 18:48, Kiuhnm kirjoitti:
> On 4/11/2012 16:01, Antti J Ylikoski wrote:
>> On 9.4.2012 21:57, Kiuhnm wrote:
>>> Do you have some real or realistic (but easy and self-contained)
>>> examples when you had to define a (multi-statement) function and pass it
>>> to another function?
>>> Thank you.
>>>
>>> Kiuhnm
>>
>> A function to numerically integrate another function comes as follows:
> [...]
>
> Thank you.
>
> Kiuhnm

Ref: numerical integration, one of the most famous methods probably is
the Romberg method:

http://en.wikipedia.org/wiki/Romberg%27s_method

the program in the Wikipedia article above is in C, but translating it
into Python would be very, very easy.

yours, Antti J Ylikoski
Helsinki, Finland, the EU
http://www.tkk.fi/~ajy/
http://www.tkk.fi/~ajy/diss.pdf
antti.ylikoski [at] gmail
--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.