On Tue, Aug 16, 2011 at 1:44 PM, Jeff Peters <je...@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
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor