[Tutor] Passing functions(with parameters) as paramiters to (looping)functions.

Jeff Peters jeffp at swva.net
Tue Aug 16 20:09:56 CEST 2011


On 08/16/2011 01:46 PM, Peter Otten wrote:
> Jeff Peters wrote:
>
>> Hi;
>>
>> I am trying to run a function inside a continuing loop, but do not seem
>> to be able to pass any parameters (arguments ) when I do so.
>> I have placed working and non-working code , with output below.
>>
>> ## This works:
>>
>> def loop(fn ):
>>       for i in range(5):
>>           fn(  )
>>
>> def this_function(a=" i am not a string"):
>>       print( a )
>>
>> loop(this_function)
>>
>> ## with output:
>>   >>>
>>    i am not a string
>>    i am not a string
>>    i am not a string
>>    i am not a string
>>    i am not a string
>>   >>>
>>
>> ## But , this does not :
>>
>> def loop(fn ):
>>       for i in range(5):
>>           fn(  )
>>
>> def this_function(a=" i am not a string"):
>>       print( a )
>>
>> loop(this_function("I am a string") )  ## note the only change is here
> You are calling this_function() and then pass the result of the function
> call to your other function loop().
>
> Instead you need another function that builds a function that calls
> this_function() with the desired argument:
>
>>>> def loop(f):
> ...     for i in range(5):
> ...             f()
> ...
>>>> def this_function(a):
> ...     print(a)
> ...
>>>> def make_function(f, arg):
> ...     def g():
> ...             f(arg)
> ...     return g
> ...
>>>> loop(make_function(this_function, "foo"))
> foo
> foo
> foo
> foo
> foo
>>>> loop(make_function(this_function, "bar"))
> bar
> bar
> bar
> bar
> bar
> Of course you could also change loop() to pass on arbitrary arguments:
>
>>>> def loop(f, *args, **kw):
> ...     for i in range(3):
> ...             f(*args, **kw)
> ...
>>>> loop(print, 1, 2)
> 1 2
> 1 2
> 1 2
>>>> loop(print, 1, 2, sep="<-->")
> 1<-->2
> 1<-->2
> 1<-->2
>
> Because building a function that just calls another function with some
> predefined arguments is a common need the standard library has
> functools.partial():
>
>>>> from functools import partial
>>>> print42 = partial(print, 42)
>>>> print42()
> 42
>>>> loop(print42)
> 42
> 42
> 42
>
> Another variant is a lambda function with a default argument:
>
>>>> loop(lambda a="whatever": print(a))
> whatever
> whatever
> whatever
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Thanks,  that  is what I needed.
not splitting the function name and argument list was
my problem.  and the  function creator  idea really appeals
thanks again - jeff




More information about the Tutor mailing list