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

Giovanni Tirloni gtirloni at sysdroid.com
Tue Aug 16 19:15:53 CEST 2011


On Tue, Aug 16, 2011 at 1:44 PM, Jeff Peters <jeffp at swva.net> 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
>
> ## With this as output:
>
> >>>
> I am a string
> Traceback (most recent call last):
>  File "/home/jeff/MyPythonStuff/**call_sub.py", line 9, in <module>
>    loop(this_function("I am a string") )
>  File "/home/jeff/MyPythonStuff/**call_sub.py", line 4, in loop
>    fn(  )
> TypeError: 'NoneType' object is not callable
> >>>
>

Your loop() function expects the parameter 'fn' to be a function that it can
then call.

In your second example, it doesn't work because you already called the
function and is passing as parameter 'fn' whatever this_function() returned.


>>> type(this_function)
<type 'function'>

>>> type(this_function("I am a string"))
I am a string
<type 'NoneType'>

If you really want this design, one way to "fix" it is to change loop() to
accept another argument that is going to be passed to the function.

def loop(fn, b):
  for i in range(5):
    fn(b)

Perhaps if you explain what you are trying to accomplish, someone can
suggest a better way to design the code.

-- 
Giovanni Tirloni
sysdroid.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110816/f0895197/attachment-0001.html>


More information about the Tutor mailing list