On Tue, Aug 16, 2011 at 1:44 PM, Jeff Peters <span dir="ltr"><<a href="mailto:jeffp@swva.net">jeffp@swva.net</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
Hi;<br>
<br>
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.<br>
I have placed working and non-working code , with output below.<br>
<br>
## This works:<br>
<br>
def loop(fn ):<br>
for i in range(5):<br>
fn( )<br>
<br>
def this_function(a=" i am not a string"):<br>
print( a )<br>
<br>
loop(this_function)<br>
<br>
## with output:<br>
>>><br>
i am not a string<br>
i am not a string<br>
i am not a string<br>
i am not a string<br>
i am not a string<br>
>>><br>
<br>
## But , this does not :<br>
<br>
def loop(fn ):<br>
for i in range(5):<br>
fn( )<br>
<br>
def this_function(a=" i am not a string"):<br>
print( a )<br>
<br>
loop(this_function("I am a string") ) ## note the only change is here<br>
<br>
## With this as output:<br>
<br>
>>><br>
I am a string<br>
Traceback (most recent call last):<br>
File "/home/jeff/MyPythonStuff/<u></u>call_sub.py", line 9, in <module><br>
loop(this_function("I am a string") )<br>
File "/home/jeff/MyPythonStuff/<u></u>call_sub.py", line 4, in loop<br>
fn( )<br>
TypeError: 'NoneType' object is not callable<br>
>>><br></blockquote><div><br></div><div>Your loop() function expects the parameter 'fn' to be a function that it can then call.</div><div><br></div><div>In your second example, it doesn't work because you already called the function and is passing as parameter 'fn' whatever this_function() returned.</div>
<div><br></div><div><br></div><div><div>>>> type(this_function)</div><div><type 'function'></div><div><br></div><div>>>> type(this_function("I am a string"))</div><div>I am a string</div>
<div><type 'NoneType'></div></div><div><br></div><div>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.</div>
<div><br></div><div>def loop(fn, b):</div><div> for i in range(5):</div><div> fn(b)</div><div><br></div><div>Perhaps if you explain what you are trying to accomplish, someone can suggest a better way to design the code.</div>
<div><br></div></div>-- <br>Giovanni Tirloni<br><a href="http://sysdroid.com" target="_blank">sysdroid.com</a><br><br>